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.

Introduction

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:

<form id="form1" runat="server">

    <h2>ASP.NET</h2>

    <p class="lead">Selcting Multiple Files using jQuery and Generic Handler</p>   

 

    <div class="form-group">

        <div>

            <asp:Label runat="server" AssociatedControlID="MultipleFilesUpload">Select Files</asp:Label>            

            <asp:FileUpload ID="MultipleFilesUpload" runat="server" AllowMultiple="true" />           

        </div>

    </div>

    <div class="form-group">

        <div class="col-md-offset-2 col-md-10">

            <asp:Button runat="server" ID="BtnUpload" Text="Upload Files" CssClass="btn btn-default" />

        </div>

    </div>   

 </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:

<script src="Scripts/jquery-1.10.2.js"></script>

<link href="Content/bootstrap.css" rel="stylesheet" />

<link href="Content/Site.css" rel="stylesheet" />

<script type="text/javascript">

    $(document).ready(function () {

        $("#BtnUpload").click(function (event) {

            var uploadfiles = $("#MultipleFilesUpload").get(0);

            var uploadedfiles = uploadfiles.files;

            var fromdata = new FormData();

            for (var i = 0; i < uploadedfiles.length; i++) {

                fromdata.append(uploadedfiles[i].name, uploadedfiles[i]);

            }

             var choice = {};

            choice.url = "UploadHandler.ashx";

            choice.type = "POST";

            choice.data = fromdata;

            choice.contentType = false;

            choice.processData = false;

            choice.success = function (result) { alert(result); };

            choice.error = function (err) { alert(err.statusText); };

            $.ajax(choice);

            event.preventDefault();

        });

    });

</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:

namespace UploadMultipleFilesApp

{

    public class UploadHandler : IHttpHandler

    {

        public void ProcessRequest(HttpContext context)

        {

            if (context.Request.Files.Count > 0)

            {

                HttpFileCollection SelectedFiles = context.Request.Files;

                for (int i = 0; i < SelectedFiles.Count; i++)

                {

                    HttpPostedFile PostedFile = SelectedFiles[i];

                    string FileName = context.Server.MapPath("~/UploadedFiles/" + PostedFile.FileName);

                    PostedFile.SaveAs(FileName);                    

                }

            }

 

            else

            {

                context.Response.ContentType = "text/plain";

                context.Response.Write("Please Select Files");

            }

 

            context.Response.ContentType = "text/plain";

            context.Response.Write("Files Uploaded Successfully!!");

        }

 

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

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

Summary

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