Home     Products      Support      Corporate     Sign In 
Support Knowledge Base, Article 980
Product
FileUp
Version
all
Title
HTML File input control filtering
Problem
Can you customize the file input control to filter by file type?
Solution

At first glance, it appears that you should be able to add filters to the file type drop-down for the HTML file input control. HTML 4.01 actually defines an ACCEPT attribute that should allow users to force the file input box to only accept certain file types. Unfortunately none of the current browsers support this attribute.

The workaround/solution for this is to use client-side script with the onsubmit event of the form to only allow the form to post if a file of a certain type is selected. Using client-side script, the extension of the selected file is parsed out to determine if it is allowed. If it is allowed, then the form is posted and the file is uploaded. If it is not allowed, an error message is displayed to the user and the form is not posted.

Be careful when scripting client-side events using a file input control. It may make sense to use the onfocus, onchange, and onblur events of the file input control, but unfortunately these events may not always work as expected in all browsers. It is best to associate the file type check with the form submission only. If you do decide to use one of these other events, be sure to test them thoroughly in a variety of browsers.

The following is an example web page with a JavaScript function that requires the selected file to have a .jpg extension:

<html>
<head>
<script type="text/javascript" language="JavaScript">
function check() {
  var ext = document.getElementById("pic").value;
  ext = ext.substring(ext.length-3,ext.length);
  ext = ext.toLowerCase();
  if(ext != 'jpg') {
    alert('You selected a .'+ext+
          ' file; please select a .jpg file instead!');
    return false; 
  } else {
    return true;
  }
}
</script>

<body>
<form name="form1" id="form1" method="post" enctype="multipart/form-data" onsubmit="return check();" action="formresp.asp">
<p>
Please select a JPEG (.jpg) file to be sent:
<br>
<input type="file" name="pic" id="pic" size="40" accept="image/jpeg">
<p>
<input type="submit" value="Upload">
</form>
</body>
</html>

Created : 4/4/2005 2:51:34 PM (last modified : 4/4/2005 3:26:36 PM)
Rate this article!
Comments