Ask your question here : ASP.NET or MVC | C# | Windows Phone
Microsoft Technology Journals by Abhimanyu K Vatsa
HOME ABOUT RAZOR BOOK MVC ASP.NET JQUERY C# VIDEOS EBOOK ARCHIVE

22 Jan 2014

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

With ASP.NET File upload control we can only upload one file at a time while HTML5 has a good notion to upload multiple files at a time. Look at the animated image given below, which was the actual framework before HTML5 equivalent updates with ASP.NET 4.5 Framework.


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


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

Here is actual File Upload control that will allow us selecting multiple files.

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

This actually generates 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 above code behind we are checking if FileUpload1 has any file selected go and upload it and write the response on the DOM, here is 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 above code behind we are checking if FileUpload1 has any file or files selected go and upload it by looping through posted files and write the response on 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 code behind will work closely similar to single file upload always.

Hope this helps.

Comment using Google Services (4 comments):

  1. Its not working in framework 4.0. So please give me solution for it.

    ReplyDelete
  2. yes its not working in asp.net 4.0 .So please give me solution for it

    ReplyDelete
  3. Its working fine in asp.net 3.5 and 4.0.
    Thank You.
    Sharath

    ReplyDelete
  4. In .Net 3.5 and 4.0 your markup in the control needs to be multiple="multiple" instead of allowmultiple="true"

    ReplyDelete