In this article I will explain with an example, how to upload multiple files using HTML5 input file in ASP.Net using C# and VB.Net.
HTML Markup
The following HTML Markup consists of a Form.
The Form has been assigned with an attribute enctype which has been set as multipart/form-data which is necessary for uploading Files.
Then, the Form consists of following controls and element:
FileUpload – For selecting file.
The HTML5 Input FileUpload element has been set with following attribute.
Attribute
multiple – This attribute allows user to select multiple files at a time. Here it is set as multiple.
Button – For uploading selected files.
The Button has been assigned with an OnClick event handler.
Label – For displaying uploaded files detail.
<form id="form1" runat="server" enctype="multipart/form-data">
<input id="fuUpload" name="fuUpload" type="file" multiple="multiple" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="OnUpload" />
<br /><br />
<asp:Label ID="lblMessage" runat="server" ForeColor="Green"></asp:Label>
</form>
Namespaces
You will need to import the following namespace.
C#
VB.Net
Uploading multiple files using HTML5 input file
When the Upload Button is clicked, first a check is performed whether the Folder (Directory) exists or not, if directory doesn’t exist then Folder (Directory) will be created.
Then, a FOR loop is executed over the uploaded files.
Inside the FOR loop, an HttpPostedFile class object is created and one by one the uploaded file is saved in the Folder (Directory).
Finally, the uploaded file is set in Label control.
C#
protected void OnUpload(object sender, EventArgs e)
{
string folderPath = Server.MapPath("~/Uploads/");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile postedFile = Request.Files[i];
string fileName = Path.GetFileName(postedFile.FileName);
postedFile.SaveAs(folderPath + fileName);
lblMessage.Text += string.Format("<b>{0}</b> uploaded.<br />", fileName);
}
}
VB.Net
Protected Sub OnUpload(ByVal sender As Object, ByVal e As EventArgs)
Dim folderPath As String = Server.MapPath("~/Uploads/")
If Not Directory.Exists(folderPath) Then
Directory.CreateDirectory(folderPath)
End If
For i As Integer = 0 To Request.Files.Count - 1
Dim postedFile As HttpPostedFile = Request.Files(i)
Dim fileName As String = Path.GetFileName(postedFile.FileName)
postedFile.SaveAs(folderPath & fileName)
lblMessage.Text += String.Format("<b>{0}</b> uploaded.<br />", fileName)
Next
End Sub
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads