ASP.Net FileUpload File Type Filter using JavaScript Validation

Updated on 04 Jul 2012,
Published on 30 Oct 2009

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. The file type filter validation enables you to validate the FileUpload control for disallowing the users to upload the files with invalid file type extensions. As each web application has different requirements where you need to integrate the FileUpload control for providing the file uploading feature. For example there is a web site 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. There may also be any other web site option that needs a file type filter validation to disallow the users from uploading images. In each type situation you have to verify the file type extension whether it matches the file extensions specified in the list of allowed file type extensions.

FileUpload Control Example:

You can see the live sample and example of FileUpload Control from the following link:

In this tutorial we will learn to implement the JavaScript validation to disable the user from uploading the images files with invalid extensions such as ".bmp", ".tiff" etc.

Sample Code to Implement the File Type Filter on FileUpload Control

HTML Code
<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Button ID="btnUpload" runat="server" Text="Upload" />
JavaScript Code
<script type="text/javascript">

    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("jpg", "png", "gif");
        
        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('Files with extension ".' + fileExtension.toUpperCase() + '" are not allowed.\n\nYou can upload the files with following extensions only:\n.jpg\n.png\n.gif\n');
            return false;
        }
        else{
            alert('File has valid extension.');
            return true;
        }
    }

</script>
C# Code
protected void Page_Load(object sender, EventArgs e)
{
    FileUpload1.Attributes.Add("onchange", "return validateFileUpload(this);");

    btnUpload.Attributes.Add("onclick", "return validateFileUpload(document.getElementById('" + FileUpload1.ClientID + "'));");
}

The C# code is required to attach the client side events to FileUpload control and Button control to call the JavaScript file type filter validation function at client side before submitting the web page to execute the server code. You can use the "onchange" client side event of the FileUpload control to call the JavaScript function when user selects the file to upload. Similarly you can attach the "onclick" client side event of the ASP.Net Button control to call the client side function.

In the JavaScript code above we have used return parameter with values true and false according the valid/invalid result of file type extension comparison performed inside the for loop. We have used the "return false" for invalid file extension and "return true" for valid file extension that will allow the web page to perform the post back when users hit the upload button.

As JavaScript validation is not sufficient because it can be disabled using web browser preferences. You must also use the C# code to validate the file type of the file specified by the user for uploading.

Output:

Get the output for above discussed code from the following link:

FileUpload File Type Filter using JavaScript

Continue to the next tutorial: ASP.Net FileUpload File type filter Validation using C# code to learn the similar functionality for disallowing the users from uploading invalid file types.

3 Responses to "ASP.Net FileUpload File Type Filter using JavaScript Validation"
HardMike
Change to: fileExtension = fileName.substr(fileName.lastIndexOf('.') + 1); Not all extensions are three digits...
Vinod
Thank you very much sir,this very helpful for me...
Aniket
First of all thanks for this useful post. But what to do in case of uploading multiple files? How to check the extensions.
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email