In this article I will explain with an example, how to upload multiple files using HTML5 input file (FileUpload control) in ASP.Net using C# and VB.Net.
Enable multiple files selection ASP.Net FileUpload
In order to enable multiple files selection in FileUpload control, you will need to make use of the HTML5 multiple attribute and set it to the ASP.Net FileUpload control.
Uploads folder location
The uploaded files will be saved in the Uploads Folder (Directory) of ASP.Net project.
HTML Markup
The HTML Markup consists of following control:
FileUpload – For selecting file.
The FileUpload has been applied with the following property:
multiple – For selecting multiple files, here it is set as multiple.
<asp:FileUpload ID="fuUpload" runat="server" multiple="multiple" />
Uploading multiple files in HTML5 supported browsers
HTML Markup
The HTML Markup consists of following controls:
FileUpload – For selecting file.
Button – For uploading selected file.
The Button has been assigned with an OnClick event handler.
Label – For displaying File Name of uploaded file.
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="OnUpload" />
<br /><br />
<asp:Label ID="lblMessage" runat="server" ForeColor="DarkGreen" />
Namespaces
You will need to import the following namespace.
C#
VB.Net
Enabling multiple files selection on Server Side
Inside the Page_Load event handler, the HTML5 multiple attribute is set to the FileUpload control.
C#
protected void Page_Load(object sender, EventArgs e)
{
fuUpload.Attributes["multiple"] = "multiple";
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
fuUpload.Attributes("multiple") = "multiple"
End Sub
Uploading multiple files using C# and VB.Net
When the Upload button is clicked, a FOR EACH loop is executed over the PostedFiles.
Then, the file is saved to the Uploads Folder (Directory) using SaveAs method of HttpPostedFile class and success message is set in the Label control.
C#
protected void OnUpload(object sender, EventArgs e)
{
foreach (HttpPostedFile postedFile in fuUpload.PostedFiles)
{
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 OnUpload(sender As Object, e As EventArgs)
For Each postedFile As HttpPostedFile In fuUpload.PostedFiles
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