Monday, January 2, 2012

How to Validate File Extension for ASP.NET FileUpload Control

In this article I am explaining How to Create a File Extension Filter for the ASP.Net FileUpload Control

On many occasions there’s a requirement to upload only selected types of files and reject the others

In this article I will explain both Client Side and Server Side validation of files using their extensions

Client Side Validation:

<script type="text/javascript">
    var validFilesTypes = ["bmp", "gif", "png", "jpg", "jpeg", "doc", "xls"];
    function ValidateFile() {
        var file = document.getElementById("<%=FileUpload1.ClientID%>");
        var label = document.getElementById("<%=Label1.ClientID%>");
        var path = file.value;
        var ext = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
        var isValidFile = false;
        for (var i = 0; i < validFilesTypes.length; i++) {
            if (ext == validFilesTypes[i]) {
                isValidFile = true;
        if (!isValidFile) {
   = "red";
            label.innerHTML = "Invalid File. Please upload a File with" +
    " extension:\n\n" + validFilesTypes.join(", ");
        return isValidFile;

As you can see above I have an array validFileTypes in which I am storing the extensions of the files that I want to allow the user to upload based. Then it loops through the array and matches that with that of the file selected by the user if it does not match user is prompted to select a valid file.

You can add the extensions of the File types that you want to allow to the array as shown in the animated GIF below.

Server Side Validation:


protected void btnUpload_Click(object senderEventArgs e)
    string[] validFileTypes = { "bmp""gif""png""jpg""jpeg""doc""xls" };
    string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
    bool isValidFile = false;
    for (int i = 0; i < validFileTypes.Length; i++)
        if (ext == "." + validFileTypes[i])
            isValidFile = true;
    if (!isValidFile)
        Label1.ForeColor = System.Drawing.Color.Red;
        Label1.Text = "Invalid File. Please upload a File with extension " +
                       string.Join(",", validFileTypes);
        Label1.ForeColor = System.Drawing.Color.Green;
        Label1.Text = "File uploaded successfully.";


    Protected Sub btnUpload_Click(ByVal sender As ObjectByVal e As System.EventArgs)
        Dim validFileTypes As String() = {"bmp""gif""png""jpg""jpeg""doc""xls"}
        Dim ext As String = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName)
        Dim isValidFile As Boolean = False
        For i As Integer = 0 To validFileTypes.Length - 1
            If ext = "." & validFileTypes(i) Then
                isValidFile = True
                Exit For
            End If
        If Not isValidFile Then
            Label1.ForeColor = System.Drawing.Color.Red
            Label1.Text = "Invalid File. Please upload a File with extension " & _
                            String.Join(",", validFileTypes)
            Label1.ForeColor = System.Drawing.Color.Green
            Label1.Text = "File uploaded successfully."
        End If
    End Sub

As you will notice the Server Side File Extension validation also use the same logic as used in client side validation checking. Here also I am maintaining a string array of valid File extensions and thenmatching it with the extension of the File that has been uploaded. The Server Side Validation Checking ensures that the even if the JavaScript Client Side Checking fails it can be validated server side.

 I am calling both Server Side and Client Side Validation methods on the Click event of the Upload button as shown below. I have also used a label which will display the error or success messages.

<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server"></asp:FileUpload>
<asp:Button ID="btnUpload" OnClick="Upload" runat="server" Text="Upload"OnClick="btnUpload_Click" OnClientClick="return ValidateFile()"></asp:Button>

No comments:

Post a Comment