Javascript Error Check for File Uploads

If your uploading a file of any decent size it will only annoy the user if they upload something wrong and get told afterwards. What we’d like to do is scan that file and make sure it’s kosher before it’s even uploaded, but unfortunately that isn’t possible with Javascript due to built in security restrictions.

Really all we know about that file is it’s name before we receive it. The only thing we can do is check the file extension to see if it is aligned with our wishes. Included here is a very simple file upload form with minimal PHP and the proper Javascript to complete this check.

Here is the HTML/Javascript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <title>Jpeg Upload</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <script type="text/javascript" language="JavaScript"><!--
    function check_extension(id) {
      var filename = document.getElementById(id).value;
      var fileext = filename.substring(filename.lastIndexOf('.')+1).toLowerCase();
      var extension = new Array('jpg','jpeg');

       for(var i = 0; i < extension.length; i++) {
         if(fileext == extension[i]) { return true; }
       }
       alert("Your upload form contains an unapproved file name.");
       return false;
    }
  //--></script>
</head>

<body>

  <form enctype="multipart/form-data" method="post" action="index.php" onsubmit="return check_extension('image_file');">
    <label for="image_file">Jpeg Image to upload: <input type="file" name="image_file" id="image_file" /></label>
    <input type="submit" name="submit" value="upload" />
  </form>

<body>
<html>

It should be fairly straightforward. In the form remember to set the onsubmit=”return check_extension(‘image_file’);” where image_file is the name of your file input. You can modify extensions in the Javascript to your preferences.

For completeness here is a working example and the source.

Leave a Reply

Your email address will not be published. Required fields are marked *