26 April 2011

File Upload Filter in JavaScript

The ASP.Net FileUpload control does not have any property to provide the functionality to filter the valid/invalid file types in the file-navigation dialog box that opens when user clicks the browse button of fileupload control. You can implement the File Type filter for FileUpload control using JavaScript client side code. This type filter validation enables you to validate the FileUpload control for disallowing the users to upload the files with invalid file type extensions.
For example there was a requirment  option to upload the User avatar that requires the file type filter validation to disable the user from uploading the files that have file extensions other than the allowed file types. Here is the sample:

<asp:FileUpload ID="dlgFileUpload" runat="server" />
<asp:LinkButton id="lnkAdd" runat="server" Text="Add" onclick="lnkAdd_Click" >asp:LinkButton>

C#code

protected void Page_Load(object sender, EventArgs e)
{
   dlgFileUpload.Attributes.Add("onchange", "return validateFileUpload(this);");
     lnkAdd.Attributes.Add("onclick", "return validateFileUpload(document.getElementById('" + dlgFileUpload.ClientID + "'));");
}

JavaScript Code:

function validateFileUpload(obj) {
    var fileName = new String();
    var fileExtension = new String();
     // store the file name into the variable   
    fileName = obj.value;
    // extract and store the file extension into another variable       
    fileExtension = fileName.substr(fileName.length - 3, 3);
    // array of allowed file type extensions       
    var validFileExtensions = new Array("rtf", "pdf", "doc","docx","msg","xlsx","txt");
    var flag = false;
    // loop over the valid file extensions to compare them with uploaded file       
    for (var index = 0; index < validFileExtensions.length; index++) {
      if (fileExtension.toLowerCase() == validFileExtensions[index].toString().toLowerCase()) {
              flag = true;
       }
     }
     // display the alert message box according to the flag value       
     if (flag == false) {
         alert('Invalid file extension.Only the following extensions are allowed:\n.rtf\n.pdf\n.doc\n.docx\n.msg\n.xls\n.xlsx\n.txt\n');
          return false;
      }
      else {
          alert('File has valid extension.');
          return true;
      }
  }

1 comment:

Prajeesh Prathap said...

Good one Jijo. Some nice ASP.NET tips already in the blog..