posted 1/14/2009 by Vijendra Shakya
When we upload a file then there is validation for the extension of the upload file because if we want to uplaod a image then there is only image related extension is allowed not any other type as .doc,.txt,.rar ...... so to avoid this we apply there extension validation on the file. when user upload the file then we first check the extension of the file if extension of the file is correct then user can upload the file otherwise there is a error message. I discuss here to ways to validate the extension of file upload.Validate through Javascript:
<script type="text/javascript" language="javascript"> function ValidateWordFileUpload() { var uploadFile = document.getElementById('<%= FileUpload1.ClientID %>'); var FilePath = uploadFile.value; if(FilePath=='') { // when user not selecte the file alert("Please Select the file"); return false; } else { // To get the extension of the file var Extension = FilePath.substring(FilePath.lastIndexOf('.') + 1).toLowerCase(); if (Extension == "doc" || Extension == "docx"||Extension == "txt" || Extension == "rtf") { return true; // Valid file type } else { alert("Please upload only .doc,.docx,.txt or .rtf file."); // file is not valid return false; } } } </script>
Check Extension on Server Side:
if (FileUpload1.HasFile == true && FileUpload1.PostedFile != null){ filename = Path.GetFileName(FileUpload1.PostedFile.FileName); string fileExtension = GetExtension(filename);if(fileExtension=="doc"||fileExtension=="docx"||fileExtension=="txt"||fileExtension=="rtf"){ // code for uplaod the file}else{string message="Please upload only .doc,.docx,.txt or .rtf file."System.Text.StringBuilder sb = new System.Text.StringBuilder();sb.Append("<script language=JavaScript>");sb.Append("alert('" + message + "');");sb.Append("</script" + ">");if (!ClientScript.IsClientScriptBlockRegistered("UserCheck")){ClientScript.RegisterClientScriptBlock(this.GetType(), "UserCheck", sb.ToString());} } }else{ string message="Please select a file."System.Text.StringBuilder sb = new System.Text.StringBuilder();sb.Append("<script language=JavaScript>");sb.Append("alert('" + message + "');");sb.Append("</script" + ">"); if (!ClientScript.IsClientScriptBlockRegistered("UserCheck")) { ClientScript.RegisterClientScriptBlock(this.GetType(), "UserCheck", sb.ToString()); }}
Hope it helps you..............
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18