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.

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

 

This actually generates the following HTML5 equivalent markup:

  1. <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.

  1. protected void btnUpload_Click(object sender, EventArgs e)  
  2. {  
  3.     if(FileUpload1.HasFile)  
  4.     {  
  5.     //upload logic  
  6.     Response.Write(FileUpload1.FileName + " - " + FileUpload1.PostedFile.ContentLength + "  
  7.     Bytes. <br />");  
  8.     }  
  9. }  

 

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.

  1. protected void btnUpload_Click(object sender, EventArgs e)  
  2. {  
  3.     if(FileUpload1.HasFiles)  
  4.     {  
  5.         foreach(var file in FileUpload1.PostedFiles)  
  6.         {  
  7.         //upload logic  
  8.             Response.Write(file.FileName + " - " + file.ContentLength + " Bytes. <br />");  
  9.         }  
  10.     }  
  11. }  

 

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.


Similar Articles