Monday, September 27, 2010

How to check upload file extension using JavaScript ?

The following is a simple JavaScript function to check the extension of an uploading file.
It will help to avoid checking the file extension in server, if the JavaScript is enabled in the browser.

We use a form for file uploading. The form is similar as follows.
<form name="a">
<input type="file" name="shw_image" id="shw_image" onchange="validateFileExtension(this.value)"/>
<input type="hidden" name="tmp_img" id="tmp_img" value="" />
</form>
Next using the JavaScript function we can find out the file extension. We are calling this function in the onchange event of the file filed.
The JavaScript function is as follows.
function validateFileExtension(fld)
{

document.getElementById("tmp_img").value= fld;
var ext = fld;
ext = ext.substring(ext.length-3,ext.length);
ext = ext.toLowerCase();
if((ext != 'jpg')&&(ext != 'gif')&&(ext != 'png')&&(ext != 'jpeg'))
{
alert('You selected a .'+ ext + ' file; \n please select a .jpg/.gif/.png/.jpeg image file');
document.frm.product_image.focus();
document.frm.product_image.value="";
document.getElementById("tmp_img").value="";
return false;
}
}
This function alerts a message if we select a file with the extension other than jpg, gif, png and jpeg.