Single File Upload to Multiple File Upload ASP.Net Web Forms

With the ASP.NET File upload control we can only upload one file at a time whereas HTML5 can upload multiple files at a time. Look at the animated image given below, that was the actual framework before HTML5 and equivalent with the ASP.NET 4.5 Framework.


In the preceding image we can’t even select multiple files. So, after the HTML5 update we can select multiples. Look at the animated image below.


You can see I just added one attribute ‘AllowMultiple="true"’ to the existing File Upload control and I’m done client-side.

Here is the actual File Upload control that will allow us to select multiple files.

<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true"/>

This actually generates the following HTML5 equivalent markup:

<input type="file" multiple="multiple" name="FileUpload1" id="FileUpload1" />

Now the code behind to handle this single file upload request and multiple file upload will be slightly different, let’s look at the single file upload code-behind.

protected void btnUpload_Click(object sender, EventArgs e)
{

    if(FileUpload1.HasFile)
    {
    //upload logic
    Response.Write(FileUpload1.FileName + " - " + FileUpload1.PostedFile.ContentLength + "
    Bytes. <br />"
);
    }
}

In the code above behind we are checking if FileUpload1 has any file selected and if so then go and upload it and write the response using the DOM, here is the output:


Now, let’s look at multiple file upload code behind.

protected void btnUpload_Click(object sender, EventArgs e)
{

    if(FileUpload1.HasFiles)
    {
        foreach(var file in FileUpload1.PostedFiles)
        {
        //upload logic
            Response.Write(file.FileName + " - " + file.ContentLength + " Bytes. <br />");
        }
    }
}

In the preceding code behind we are checking if FileUpload1 has any file or files selected and if so then go and upload it by looping through the posted files and write the response using the DOM, here is output:


This is super cool.

What about old browsers that does not support HTML5?

Well old browsers will simply ignore this new attribute multiple="multiple" and the code behind will work as a single file upload always.

Hope this helps.

Up Next
    Ebook Download
    View all
    Learn
    View all