To restrict File upload control to accept only specified types to be uploaded using Java Script

Prabhukiran345
Posted by Prabhukiran345 under JavaScript category on | Points: 40 | Views : 4273
Here is the code to restrict our file upload control to accept only specified file types to be uploaded,using Javascript.

In this example i am allowing only image files of type ".jps,.jpeg,.png,.gif"

JavaScript Code:
File Upload Control:
<input type="file" id="uploadImg" name="upload" onchange="checkfile(this);" />

function checkfile(sender)
{
var validExts = new Array(".jpg", ".JPG", ".jpeg", ".JPEG", ".gif", ".png", '.PNG');
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));

//For Indexof() -IE < 9
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function (elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
if (validExts.indexOf(fileExt) < 0)
{
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
sender.value = '';
return false;
}
else
{
return true;
}
}

Comments or Responses

Login to post response