In this article I will explain with an example, how to upload multiple files using FileUpload Control in ASP.Net 4.5 using C# and VB.Net.
This article makes use of ASP.Net version 4.5.
HTML Markup
The following HTML Markup consists of:
FileUpload – For selecting file.
Properties:
AllowMultiple – It allows user to select multiple files.
Button – For uploading selected file.
The Button has been assigned with an OnClick event handler.
Label – For displaying message.
<asp:FileUpload ID="fuUpload" runat="server" AllowMultiple="true" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="OnUpload" />
<hr />
<asp:Label ID="lblMessage" runat="server" ForeColor="Green"></asp:Label>
Namespaces
You will need to import the following namespace.
C#
VB.Net
Uploading multiple files using FileUpload Control
When the Upload Button is clicked, first a check is performed whether the Folder (Directory) exists or not if it does not then, the Folder (Directory) is created.
Then, a FOREACH 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 message is displayed using the Label control.
C#
protected void OnUpload(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 fuUpload.PostedFiles)
{
//Save the File to the Directory (Folder).
postedFile.SaveAs(folderPath + Path.GetFileName(postedFile.FileName));
}
//Display the success message.
lblMessage.Text = string.Format("{0} files have been uploaded successfully.", fuUpload.PostedFiles.Count);
}
VB.Net
Protected Sub OnUpload(ByVal sender As Object, ByVal 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
For Each postedFile As HttpPostedFile In fuUpload.PostedFiles
'Save the File to the Directory (Folder).
postedFile.SaveAs(folderPath & Path.GetFileName(postedFile.FileName))
Next
'Display the success message.
lblMessage.Text = String.Format("{0} files have been uploaded successfully.", fuUpload.PostedFiles.Count)
End Sub
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads