This article explains about file upload control validation in JavaScript. By default when the user selects invalid format using the file upload control, the server control will not clear the content automatically. using the below code we can check the file extension and if it is not valid file extension then the textbox is cleared. This happens on the client side only using JavaScript.
First lets put a FileUpload control in your aspx page and then call our validation function on client click. Here is the html FileUpload control code.
<asp:fileupload id="FileUpload1" runat="server" />
<input id="btnUpload" onclick="checkFileExtensionLogo('FileUpload1')" type="button" value="Upload" />
when user clicked on the above button we are calling our client side function which validate the extension of the file as well as clears the content.
function checkFileExtensionLogo(Obj)
{
var elm=document.getElementById(Obj);
var filePath = elm.value;
if(filePath.indexOf('.') == -1)
return false;
var validExtensions = new Array();
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
validExtensions[0] = 'jpg';
for(var i = 0; i < validExtensions.length; i++) {
if(ext == validExtensions[i])
return true;
}
alert('Invalid file, only JPG files are allowed.');
/* start: The below code clears the content in the file upload control.*/
var who =elm;
who.value="";var who2= who.cloneNode(false);
who2.onchange= who.onchange;
who.parentNode.replaceChild(who2,who);
/* End */
return false;
}
The last few lines of code is the core part of this logic, it clears the content in the file upload control.