Uploading Multiple Files Using jQuery and Generic Handler in ASP.Net 4.5


This article describes how to upload multiple files in ASP.NET Web Forms using the jQuery and Generic Handler. Generally developers use the FileUpload Server control to upload files from the client machine to the server that is rendered as as an INPUT element and set to file and allows you to select the file or multiple files. We can use the jQuery to make an Ajax call to the server and POST the multiple selected files to the Generic Handler instead of a full page postback.

In this article for developing the application, I am using Visual Studio 2013 that has the framework 4.5.1. So, let's get started with the following procedure.

Creating WebForms

Step 1: Open Visual Studio and create the ASP.NET Web Application.

Step 2: Select the WebForms project template to proceed.

WebForms Project Template in VS 2013

Visual Studio automatically creates the project and adds files and folders to the project by default.

Creating WebForm

Step 1: Just right-click on the project and add a new folder named "UploadedFiles".

Creating New Folder in WebForms Project

Step 2: Just right-click on the project and add a new Web Form and replace the body content from the following content:

  1. <form id="form1" runat="server">  
  2.     <h2>ASP.NET</h2>  
  3.     <p class="lead">Selcting Multiple Files using jQuery and Generic Handler</p>     
  4.     <div class="form-group">  
  5.         <div>  
  6.             <asp:Label runat="server" AssociatedControlID="MultipleFilesUpload">Select Files</asp:Label>              
  7.             <asp:FileUpload ID="MultipleFilesUpload" runat="server" AllowMultiple="true" />  
  8.         </div>  
  9.     </div>  
  10.     <div class="form-group">  
  11.         <div class="col-md-offset-2 col-md-10">  
  12.             <asp:Button runat="server" ID="BtnUpload" Text="Upload Files" CssClass="btn btn-default" />  
  13.         </div>  
  14.     </div>  
  15.  </form>

In the code above, I used the AllowMultiple property of FileUpload that is set to true. It is one of the HTML 5 features used in here.

Step 2: Now in the <head> section add the following code:

  1. <script src="Scripts/jquery-1.10.2.js"></script>  
  2. <link href="Content/bootstrap.css" rel="stylesheet" />  
  3. <link href="Content/Site.css" rel="stylesheet" />  
  4. <script type="text/javascript">  
  5.     $(document).ready(function () {  
  6.         $("#BtnUpload").click(function (event) {  
  7.             var uploadfiles = $("#MultipleFilesUpload").get(0);  
  8.             var uploadedfiles = uploadfiles.files;  
  9.             var fromdata = new FormData();  
  10.             for (var i = 0; i < uploadedfiles.length; i++) {  
  11.                 fromdata.append(uploadedfiles[i].name, uploadedfiles[i]);  
  12.             }  
  13.             var choice = {};  
  14.             choice.url = "UploadHandler.ashx";  
  15.             choice.type = "POST";  
  16.             choice.data = fromdata;  
  17.             choice.contentType = false;  
  18.             choice.processData = false;  
  19.             choice.success = function (result) { alert(result); };  
  20.             choice.error = function (err) { alert(err.statusText); };  
  21.             $.ajax(choice);  
  22.             event.preventDefault();  
  23.         });  
  24.     });  
  25. </script>

By the code above, the files are selected in the file upload control using the files property of the DOM element. the loop iterates through all the files then calls the append() method of the FormData to add the files to the FormData object.

Now, the data is to be sent to the server. The $.ajax() is used to transfer the data. The choice object supplies various settings such as target URL and HTTP method. We have set the URL property to the GenericHandler file named UploadHandler.ashx . We have set the contentType and processData property to false with which the jQuery won't URL encode the data while sending to the server. The success and error properties are used to display the messages through an alert.

Creating Generic Handler

Step 1: Add the Generic Handler by right-clicking on the project named UploadHandler.

Adding Generic Handler in Project

Step 2: Modify the code with the following code:

  1. namespace UploadMultipleFilesApp  
  2. {  
  3.     public class UploadHandler : IHttpHandler  
  4.     {  
  5.         public void ProcessRequest(HttpContext context)  
  6.         {  
  7.             if (context.Request.Files.Count > 0)  
  8.             {  
  9.                 HttpFileCollection SelectedFiles = context.Request.Files;  
  10.                 for (int i = 0; i < SelectedFiles.Count; i++)  
  11.                 {  
  12.                     HttpPostedFile PostedFile = SelectedFiles[i];  
  13.                     string FileName = context.Server.MapPath("~/UploadedFiles/" + PostedFile.FileName);  
  14.                     PostedFile.SaveAs(FileName);                      
  15.                 }  
  16.             }  
  17.             else  
  18.             {  
  19.                 context.Response.ContentType = "text/plain";  
  20.                 context.Response.Write("Please Select Files");  
  21.             }  
  22.             context.Response.ContentType = "text/plain";  
  23.             context.Response.Write("Files Uploaded Successfully!!");  
  24.         }  
  25.         public bool IsReusable  
  26.         {  
  27.             get  
  28.             {  
  29.                 return false;  
  30.             }  
  31.         }  
  32.     }  

Here we can see that the files that are posted to the server and can be accessed using the Request object. Each element of the HttpFileCollection is of type HttpPostedFile. FileName property is used to get the file name of posted file and return it and the same name id used to save the file.

Run WebForm

Now run the webform and choose the files as shown below that the files are selected.

Selecting Multiple Files

After clicking on Upload Files, the message is generated.

Alert Message in the WebForm


This article described how to select multiple files and upload them using jQuery and Generic Handler in ASP.NET Web Forms. Happy Coding and thanks for reading. 

To download the code, please refer to: UploadMultipleFiles

Similar Articles