Home Asp.net Validate File Extension During File Upload using JavaScript in Asp.net

Validate File Extension During File Upload using JavaScript in Asp.net

6
0

In my previous tutorial, I’d explained how to upload and download files from the server folder in asp.net, how to send test mail using gmail smtp settings, how to export gridview selected rows to word excel text and pdf and other more cracking tutorials on Asp.net, JavaScript, jQuery here.

Now here in this tutorial, I’ll explain how to check or validate file extensions during/before file upload from client-side using javascript and from server-side using custom validator. Like say for example, if you want to allow users to upload only images, you can allow users to upload only files with .jpg, .jpeg, .png, .gif extensions.

Get or Validate File Extentsions from Client-side – [JavaScript]

First add asp.net file upload control by simply copy and paste following single line of code to your .aspx page:

<asp:FileUpload ID="fuFileUploader" runat="server" />

Now here is the JavaScript that validate the file extension from client-side:

<script type="text/javascript">
       function ValidateFileUploader(source, args) {
               var fuFileUploader = document.getElementById('<%= fuFileUploader.ClientID %>');
               var filePath = fuFileUploader.value;
               //defaults to "false" means invalid file or file extenstion
               args.IsValid = false;
               if (filePath) {
                       var fileExtension = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
                       //replace your file extensions for validation
                       var validFilesExtensions = ["jpg", "png", "gif", "doc", "xls"];
                       for (var i = 0; i < validFilesExtensions.length; i++) {
                               if (fileExtension == validFilesExtensions[i]) {
                                       //valid file extension so returns true & get out from loop
                                       args.IsValid = true; break;
                               }
                       }

                       if (!args.IsValid) {
                               //not a valid file extension so remove file and show message
                               fuFileUploader.value = "";
                       }
                       else {
                               //valid file extension do your stuff with valid file
                       }
               }
               else {
                       //no file selected
               }
       }
</script>

Get or Validate File Extentsions from Server-side – [C#/Vb.net]

Following is the complete HTML markup code for file upload and custom validator control for .aspx page:

<asp:FileUpload ID="fuFileUploader" runat="server" />
<asp:CustomValidator ID="cvFileUploader" ControlToValidate="fuFileUploader" runat="server"
OnServerValidate="cvFileUploader_ServerValidate" ClientValidationFunction="ValidateFileUploader"
ErrorMessage="Invalid File Extension" ForeColor="Red">
</asp:CustomValidator>

Now here is the code that is used to validate the file extension from code-behind:

For C#:

protected void cvFileUploader_ServerValidate(object source, ServerValidateEventArgs args)
{
       args.IsValid = false; //default to false means invalid
       if (fuFileUploader.PostedFile != null && fuFileUploader.PostedFile.ContentLength > 0)
       {
               string[] fileAllowedExtenstions = { "jpg", "png", "gif", "doc", "xls" };
               string fileName = fuFileUploader.PostedFile.FileName; //get filename
               string fileExtensions = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
               foreach (var extension in fileAllowedExtenstions)
               {
                       if (fileExtensions == extension)
                       {
                               //valid file extension so returns true & get out from loop
                               args.IsValid = true;
                               break;
                       }
               }

               if (!args.IsValid)
               {
                       //not a valid file extension
                       lblMsg.Text = "Invalid: Allowed file extensions are jpg, png, gif, doc, xls";
               }
               else
               {
                       //valid file extension
               }
       }
       else
       {
               //no file selected
               lblMsg.Text = "Error: Please select a file to upload!";
       }
}

For Vb.net:

Protected Sub cvFileUploader_ServerValidate(ByVal source As Object,
ByVal args As ServerValidateEventArgs)
               args.IsValid = False 'default to false means invalid
               If fuFileUploader.PostedFile IsNot Nothing AndAlso
               fuFileUploader.PostedFile.ContentLength > 0 Then
                       Dim fileAllowedExtenstions() As String = {"jpg", "png", "gif", "doc", "xls"}
                       Dim fileName As String = fuFileUploader.PostedFile.FileName 'get filename
                       Dim fileExtensions As String =
                       fileName.Substring(fileName.LastIndexOf("."c) + 1).ToLower()
                       For Each extension In fileAllowedExtenstions
                               If fileExtensions = extension Then
                                       'valid file extension so returns true & get out from loop
                                       args.IsValid = True
                                       Exit For
                               End If
                       Next extension

                       If Not args.IsValid Then
                               'not a valid file extension
                               lblMsg.Text = "Invalid: Allowed file extensions are jpg, png, gif, doc, xls"
                       Else
                               'valid file extension
                       End If
               Else
                       'no file selected
                       lblMsg.Text = "Error: Please select a file to upload!"
               End If
       End Sub

Example Result

Validate file extension during uploading files in asp.net

Download Example

[wpdm_file id=13]

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!