Validate file extension while uploading image or file through File Upload control using JavaScript in asp.net | Use of CustomValidator control to validate file extension before uploading image or file through FileUpload control in asp.net

Introduction: In previous articles i explained How to Drag & drop to upload multiple files using AjaxFileUpload like Facebook and  show Message box in asp.net website using JavaScript and how to redirect visitor from one website to another website using java script and How to call java script function from code behind file in asp.net  and How to show Validation guidelines in web forms using JavaScript in Asp.net ?.
Now in this article i am going to explain with example How to validate the file before uploading by checking file extension or we can say restricting the user to upload only specific type of files though FileUpload control using javascript and customvalidator validation control.

Description: Sometimes it is required to validate the file extension before uploading file i.e. you want that user can upload only the files that you want e.g. if you want the user to upload only jpg, jpeg, png, gif, doc, docx, xls, xlsx files then you have to check the extension of the file the user is going to upload and validate it.

Implementation: Let's create an asp.net web application to demonstrate it.

  • First of all write the JavaScript function to validate file extension in the Head tag of your design page(.aspx) as:
Note: We are creating JavaScript function to validate the file extension and calling that function on the CustomValidator control. So this article also demonstrates the use of CustomValidator control.

<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
        function ValidateFileUploadExtension(Source, args) {
            var fupData = document.getElementById('<%= FileUpload1.ClientID %>');
            var FileUploadPath = fupData.value;

            if (FileUploadPath == '') {
                // There is no file selected
                alert("Please select file to upload");
            }
            else {
                var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

                if (Extension == "gif" || Extension == "jpeg" || Extension == "jpg" || Extension == "png" || Extension == "doc" || Extension == "docx" || Extension == "xls" || Extension == "xlsx")
                 {
                    args.IsValid = true; // Valid file type
                }
                else {
                    args.IsValid = false; // Not valid file type
                }
            }
        }
</script>
</head>

HTML Source Code
  • Place a FileUpload control on design page(.aspx)
  <asp:FileUpload ID="FileUpload1" runat="server" />
  <asp:CustomValidator ID="CustomValidator1" runat="server"
 ClientValidationFunction="ValidateFileUploadExtension" ErrorMessage="Please select valid gif/jpeg/jpg/png/doc/docx/xls/xlsx file" Font-Size="16px" ForeColor="red"></asp:CustomValidator>

<asp:Button ID="btnUpload" runat="server"  Text="upload"  onclick="btnUpload_Click" />

Asp.Net C# Code to Validate file extension and upload image using cutomvalidator
  • In the code behind (.aspx.cs) file write the code:
    protected void btnUpload_Click(object sender, EventArgs e)
    {
            //write code to upload file
            string filePath = (Server.MapPath("Uploads/") + Guid.NewGuid() + FileUpload1.PostedFile.FileName);
            FileUpload1.SaveAs(filePath);
    }

Asp.Net VB Code to Validate file extension and upload image using cutomvalidator
  • In the code behind (.aspx.vb) file write the code:
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)     
                                         'write code to upload file
                                         Dim filePath As String = (Server.MapPath("Uploads/") + Guid.NewGuid() + FileUpload1.PostedFile.FileName)
                                         FileUpload1.SaveAs(filePath)                   
End Sub

 Note: In this example Uploaded file will be saved in the Uploads folder. You can create a folder with different name and Replace the Uploads folder with the name of your Folder.

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Previous
Next Post »

5 comments

Click here for comments
September 20, 2013 ×

your welcome Pradnyankar Badge..keep reading :)

Reply
avatar
Anonymous
admin
March 09, 2015 ×

Thanks.It was very useful.

Reply
avatar
March 09, 2015 ×

Thanks for your feedback..:)

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..