Warning: include_once(/home/llynix/llynix.com/wp-content/plugins/wordpress-support/wordpress-support.php): failed to open stream: Permission denied in /home/llynix/llynix.com/wp-settings.php on line 304

Warning: include_once(): Failed opening '/home/llynix/llynix.com/wp-content/plugins/wordpress-support/wordpress-support.php' for inclusion (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear') in /home/llynix/llynix.com/wp-settings.php on line 304
Blog Archive » Javascript Error Check for File Uploads » llynix.com

Javascript Error Check for File Uploads

June 26th, 2007 @

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