In this article I will explain how to select upload multiple files in browsers that support HTML5 using FileUpload control in in ASP.Net 2.0, 3.0, 3.5 and 4.0.
ASP.Net 4.5 added a new feature to FileUpload control i.e. AllowMultiple which allows user to select multiple files in browsers that support HTML5. ASP.Net versions 2.0, 3.0, 3.5 and 4.0 does not support AllowMultiple feature.
Enable multiple files selection ASP.Net FileUpload
In order to enable multiple files selection in ASP.Net FileUpload, you will need to make use of the HTML5 multiple attribute and set it to the ASP.Net FileUpload control in the following ways.
Direct way
This is easiest and dirty way though it works but it will raise warnings from Visual Studio.
<asp:FileUpload ID="FileUpload1" runat="server" multiple = "multiple" />
Code Behind way
Inside the Page Load event, you will need to set the HTML5 multiple attribute for the ASP.Net FileUpload control as shown below.
C#
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes["multiple"] = "multiple";
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
FileUpload1.Attributes("multiple") = "multiple"
End Sub
Uploading multiple files in HTML5 supported browsers
HTML Markup
The following HTML Markup consists of an ASP.Net FileUpload control, a Button and a Label.
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" />
<br />
<br />
<asp:Label ID="lblMessage" runat="server" ForeColor = "DarkGreen" />
Inside the Page Load event of the page, the HTML5 multiple attribute is set to the ASP.Net FileUpload control.
When the Upload Button is clicked, a loop is executed over the Request.Files collection and one by one each file is saved in to the Uploads folder.
C#
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes["multiple"] = "multiple";
}
protected void Upload(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile postedFile = Request.Files[i];
if (postedFile.ContentLength > 0)
{
string fileName = Path.GetFileName(postedFile.FileName);
postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
lblMessage.Text += string.Format("<b>{0}</b> uploaded.<br />", fileName);
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
FileUpload1.Attributes("multiple") = "multiple"
End Sub
Protected Sub Upload(sender As Object, e As EventArgs)
For i As Integer = 0 To Request.Files.Count - 1
Dim postedFile As HttpPostedFile = Request.Files(i)
If postedFile.ContentLength > 0 Then
Dim fileName As String = Path.GetFileName(postedFile.FileName)
postedFile.SaveAs(Server.MapPath("~/Uploads/") & fileName)
lblMessage.Text += String.Format("<b>{0}</b> uploaded.<br />", fileName)
End If
Next
End Sub
Screenshot
Downloads