December 2017 : Online courses in ASP.NET MVC and Angular 4. Conducted by Bipin Joshi. Read more...
Registration for December 2017 batches of ASP.NET MVC / Core and Angular 4 online courses have already started. Conducted by Bipin Joshi. Book your seat today ! Click here for more details.

Uploading Files Using ASP.NET Web Forms, Generic Handler and jQuery

In order to upload files from the client machine to the server ASP.NET developers use FileUpload server control. The FileUpload server control essentially renders an INPUT element with its type set to file and allows you to select one or more files. The actual upload operation is performed only when the form is posted to the server. Instead of making a full page postback you can use jQuery to make an Ajax call to the server and POST the selected files to a generic handler (.ashx). The generic handler can then save the files to a specified folder. The remainder of this post shows how this can be accomplished.

Begin by creating a new ASP.NET project and add a web form to it. Place a FileUpload control and a Button control on it. The following markup shows the markup of these controls:

<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload Selected File(s)" />
</form>

Notice that the AllowMultiple property of the FileUpload control is set to true. This was you can select multiple files at a time (this is actually one of the HTML5 features).

Next, add jQuery library to your project and add a <script> reference to it in the <head> section of your web form.

 <script src="scripts/jquery-2.0.0.js"></script>

Then add a <script> block and key-in the following code to it:

<script type="text/javascript">
$(document).ready(function () {
  $("#Button1").click(function (evt) {
    var fileUpload = $("#FileUpload1").get(0);
    var files = fileUpload.files;

    var data = new FormData();
    for (var i = 0; i < files.length; i++) {
      data.append(files[i].name, files[i]);
    }

    var options = {};
    options.url = "FileUploadHandler.ashx";
    options.type = "POST";
    options.data = data;
    options.contentType = false;
    options.processData = false;
    options.success = function (result) { alert(result); };
    options.error = function (err) { alert(err.statusText); };
  
   $.ajax(options);
 
   evt.preventDefault();
  });
});
</script>

The above jQuery code gets the list of files selected in the FileUpload control using files property of the DOM element. It then creates an instance of FormData object. A for loop iterates through all the selected files and calls append() method of FormData to add the files to the FormData object. The append() method takes two parameters viz. name of the item being added and the item itself.

This FormData needs to be sent to the server for further processing. To facilitate this data transfer you use $.ajax() of jQuery. The options object supplies various settings such as target URL and HTTP method. Notice that the url property is set to FileUploadHandler.ashx. You will develop this generic handler soon. The data property is set to the FormData object you created earlier. The contentType and processData properties are set to false. This way jQuery won't URL encode  the data while sending it to the server. The success and error functions simply display the corresponding messages in an alert.

Now, add a Generic Handler to the project and name it as FileUploadHandler.ashx. Add the following code to the generic handler:

namespace jQueryFileUploadDemo
{
    public class FileUploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection files = context.Request.Files;
                for (int i = 0; i < files.Count;i++ )
                {
                    HttpPostedFile file = files[i];
                    string fname = context.Server.MapPath("~/uploads/" + file.FileName);
                    file.SaveAs(fname);
                }
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("File(s) Uploaded Successfully!");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

As you can see the files POSTed to the server can be accessed using the Files collection of the Request object. Each element of the HttpFileCollection is of type HttpPostedFile. A for loop iterates through the files collection and grabs each file in an HttpPostedFile variable. The FileName property of the HttpPostedFile class returns the filename of the file. Based on this filename its server side path is determined (this example stores the files in Uploads folder). The SaveAs() method of the HttpPosted file class saves the file to a specified folder.

That's it! Run the web form and try uploading one or more files to the server. If everything is fine you should get the "File(s) Uploaded Successfully!" message displayed in the browser.


Bipin Joshi is a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 27 June 2013


Tags : ASP.NET Web Forms jQuery HTML5