In this article I will explain with an example, how to upload multiple files with ASP.Net 4.5 FileUpload control in Visual Studio 2012 and Visual Studio 2013 using C# and VB.Net.
The HTML5 FileUpload control supports selection of multiple files at once and all the selected files are uploaded together.
HTML Markup
The following HTML Markup consists of an ASP.Net FileUpload control, an ASP.Net Button and an ASP.Net Label control.
The FileUpload control has been set with AllowMultiple property to True.
The ASP.Net Button has been assigned with an OnClick event handler.
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="UploadMultipleFiles" />
<hr />
<asp:Label ID="lblSuccess" runat="server" ForeColor ="Green" />
Namespaces
You will need to import the following namespace.
C#
VB.Net
Uploading multiple files with ASP.Net 4.5 FileUpload
When the Upload Button is clicked, following event handler is executed.
Inside this event handler, first a check is performed whether the Folder (Directory) exists. If it does not then, the Folder (Directory) is created.
Next, a loop is executed over the FileUpload PostedFiles property which holds the uploaded files.
Inside the loop, the names of the files are extracted and then the files are stored in Folder (Directory).
Finally, the success message is displayed using the Label control.
C#
protected void UploadMultipleFiles(object sender, EventArgs e)
{
string folderPath = Server.MapPath("~/Files/");
//Check whether Directory (Folder) exists.
if (!Directory.Exists(folderPath))
{
//If Directory (Folder) does not exists. Create it.
Directory.CreateDirectory(folderPath);
}
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
//Save the File to the Directory (Folder).
postedFile.SaveAs(folderPath + Path.GetFileName(postedFile.FileName));
}
//Display the success message.
lblSuccess.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
}
VB.Net
Protected Sub UploadMultipleFiles(sender As Object, e As EventArgs)
Dim folderPath As String = Server.MapPath("~/Files/")
'Check whether Directory (Folder) exists.
If Not Directory.Exists(folderPath) Then
'If Directory (Folder) does not exists. Create it.
Directory.CreateDirectory(folderPath)
End If
ForEach postedFile As HttpPostedFile In FileUpload1.PostedFiles
'Save the File to the Directory (Folder).
postedFile.SaveAs(folderPath & Path.GetFileName(postedFile.FileName))
Next
'Display the success message.
lblSuccess.Text = String.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count)
End Sub
Screenshot
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.
* All browser logos displayed above are property of their respective owners.
Downloads