Search This Blog

Friday, September 2, 2016

Upload multiple files with ASP.Net 4.5 FileUpload control in Visual Studio 2012 and 2013

HTML Markup
The HTML markup consists of an ASP.Net FileUpload control with AllowMultiple property set to true, a Button control for triggering the upload of files and a Label for displaying the success message after the files are uploaded.
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick ="UploadMultipleFiles" accept ="image/gif, image/jpeg" />
<hr />
<asp:Label ID="lblSuccess" runat="server" ForeColor ="Green" />

Namespaces
You will need to import the following namespace.
C#
using System.IO;

VB.Net
Imports System.IO


Upload multiple files with ASP.Net 4.5 FileUpload control in Visual Studio 2012 and 2013
Inside the Button click event handler, 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.
Finally the success message is displayed using the Label control.
C#
protected void UploadMultipleFiles(object sender, EventArgs e)
{
     foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
     {
          string fileName = Path.GetFileName(postedFile.FileName);
          postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
     }
     lblSuccess.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
}



No comments:

Post a Comment