Thursday, 3 October 2013

Upload Multiple Files using ASP.NET 4.5

Leave a Comment
In earlier versions of ASP.NET (version less than 4.5), we didn't have any inbuilt functionality to upload multiple files at once. ASP.NET FileUpload control allows uploading only one file at a time. Alternate solutions to upload multiple files are third party controls like Telerik or Devexpress. We can also use various jQuery Plugin like Uploadify to achieve similar functionality. 
In ASP.NET 4.5, we can upload multiple files at once using ASP.NET FileUpload control. In ASP.NET 4.5, FileUpload Control support HTML5 multiple attribute.

Below are the steps to upload multiple files using ASP.NET 4.5 :
  1. In Visual Studio 2012, create a new website using .Net 4.5 framework.
  2. Add a new web form (for example FileUpload.aspx) in newly created website.
  3. In code-beside file of FileUpload.aspx, write following code for FileUpload Control:
    <asp:fileupload AllowMultiple="true" id="MultipleFileUpload" runat="server">
    In above code, I have set AllowMultiple property of FileUpload Control to true.
  4.  Add one button to upload multiple files using FileUpload Control on button click.
    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
  5. Write below code on button click event handler.
    protected void btnUpload_Click(object sender, EventArgs e)
            if (MultipleFileUpload.HasFiles)
                StringBuilder UploadedFileNames = new StringBuilder();
                foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
                    string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                    uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Files/"), FileName));
                    UploadedFileNames.AppendFormat("{0}<br />", FileName);
                Response.Write("Uploaded Files are : <br/>" + UploadedFileNames);
  6. On button click, I am checking for multiple files and saving those files into Files folder of web application.
  7. Compile source code and run the website application.
I had selected five images to upload. Once I had clicked on Upload button, all five images were uploaded successfully in Files folder. Source code can be downloaded from Github.
All HTML5 enabled web browsers support above functionality. I have tested this feature in IE 10, Mozilla and Google Chrome. For all other browsers, it will work like normal ASP.NET FileUpload Control.
Comments and suggestions are most welcome. Happy coding! 


Post a Comment