Friday, December 23, 2011

Async file upload with jquery and ASP.NET

Recently before some I was in search of good asynchronous file upload control which can upload file without post back and I have don’t have to write much custom logic about this. So after searching it on internet I have found lots of options but some of the options were not working with ASP.NET and some of work options are not possible regarding context to my application just like AsyncFileUpload from Ajax toolkit.As in my application we were having old version of Ajax toolkit and if we change it than other controls stopped working. So after doing further search on internet I have found a great Juqery plugin which can easily be integrated with my application and I don’t have to write much coding to do same.

So I have download that plug from the following link. This plug in created by yvind Saltvik

After downloading the plugin and going through it documentation I have found that I need to write a page or generic handler which can directly upload the file on the server. So I have decided to write a generic handler for that as generic handler is best suited with this kind of situation and we don’t have to bother about response generated by it.

So let’s create example and In this example I will show how we can create async file upload without writing so much code with the help of this plugin. So I have create project called JuqeryFileUpload and our need for this example to create a generic handler. So let’s create a generic handler. You can create a new generic handler via right project-> Add –>New item->Generic handler just like following.


I have created generic handler called AjaxFileuploader and following is simple code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace JuqeryFileUPload
   /// <summary>
   /// Summary description for AjaxFileUploader
   /// </summary>
   public class AjaxFileUploader : IHttpHandler

       public void ProcessRequest(HttpContext context)
           if (context.Request.Files.Count > 0)
               string path = context.Server.MapPath("~/Temp");
               if (!Directory.Exists(path))

               var file = context.Request.Files[0];

               string fileName;

               if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                   string[] files = file.FileName.Split(new char[] { '\\' });
                   fileName = files[files.Length - 1];
                   fileName = file.FileName;
               string strFileName=fileName ;
               fileName = Path.Combine(path, fileName);

               string msg = "{";
               msg += string.Format("error:'{0}',\n", string.Empty);
               msg += string.Format("msg:'{0}'\n", strFileName);
               msg += "}";


       public bool IsReusable
               return true;

As you can see in above code.I have written a simple code to upload a file from received from file upload plugin into the temp directory on the server and if this directory is not there on the server then it will also get created by the this generic handler.At the end of the of execution I am returning the simple response which is required by plugin itself. Here in message part I am passing the name of file uploaded and in error message you can pass error if anything occurred for the time being I have not used right now.

As like all jQuery plugin this plugin also does need jQuery file and there is another .js file given for plugin called ajaxfileupload.js. So I have created a test.aspx to test jQuery file and written following html for that .

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="JuqeryFileUPload.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
   <script type="text/javascript" src="jquery.js"></script>
   <script type="text/javascript" src="ajaxfileupload.js"></script>
   <form id="form1" runat="server">
         <input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input">
         <button id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>
         <img id="loading" src="loading.gif" style="display:none;">

As you can see in above code there its very simple. I have included the jQuery and ajafileupload.js given by the file upload give and there are three elements that I have used one if plain file input control you can also use the file upload control and but here I don’t need it so I have user file upload control. There is button there called which is calling a JavaScript function called “ajaxFileUpload” and here we will write a code upload that. There is an image called loading which just an animated gif which will display during the async call of generic handler. Following is code ajaxFileUpload function.

<script type="text/javascript">
   function ajaxFileUpload() {
   .ajaxStart(function () {
   .ajaxComplete(function () {

           url: 'AjaxFileUploader.ashx',
           secureuri: false,
           fileElementId: 'fileToUpload',
           dataType: 'json',
           data: { name: 'logan', id: 'id' },
           success: function (data, status) {
               if (typeof (data.error) != 'undefined') {
                   if (data.error != '') {
                   } else {
           error: function (data, status, e) {

       return false;


As you can see in above code I have putted our generic handler url which will upload the file on server as url parameter. There is also parameter called secureURI is required to be true if you are uploading file through the secure channel and as a third parameter we have to pass a file upload control id which I have already passed and in fourth parameter we have to passed busy indicator which I have also passed. Once we passed all the parameter then it will call a method for plugin and will return response in terms of message and error. So There is two handler function written for that.

That’s it. Our async file upload is ready. As you can easily integrate it and also it working fine in all the browser. Hope you like it. Stay tuned for more. Till then happy programming..


  1. how to put a progress bar there?

  2. javascript file :
    ajaxfileupload.js ?
    From Where I can collect it.

  3. You can download that from -

  4. this plugin for async upload only. There are other plugin available for others also.

  5. @NEOLEO - Source code is already there in post!!

  6. I was able to modify this to validate file types. But when I drop this usercontrol twice in a page-the first control gives syntaxErr. How do I fix this?

  7. You need to take that control for upload server side. In example I have taken it via normal HTML control.

  8. Hi there,
    How can I determine file size and file type before uploading ?


  9. You can get file type by extension and extension will be get by following.

    string ext=Path.GetExtension(context.Request.Files[0]);

  10. Here's how you can get file size.

  11. The correct answer there says "You can't"...

    Any idea how I can get the file size on client?

  12. Thanks for your answer. Do you know of a way to get file type on client ?

  13. @jalpesh07 Is there a way to get file type and file size in Javascript ?

  14. This is how I can get file size on javascript

  15. I have assembled this code but not working. Can you help me to identify what I'm missing here?

  16. can you send me your code offline so that I can see and let you know

  17. Thank you for the prompt response. I have posted my code here.

    Please help!

  18. Please put jquery.js first then that file upload js its having dependency on that. Also please remove that post.

  19. still not working: If I keep the "$.ajaxFileUpload" then it doesn't go inside the script and If I keep "$.ajax" in ajaxFileUpload() javascript function then It goes into code behind but showing file count zero in handler "if (context.Request.Files.Count > 0)".

  20. send me your project in zip file I will check and get back to you.

  21. Hello, if I have others (input text, list, textbox, etc..) as shipping and receiving as the ashx.

  22. Hi, this is not working in IE9 and IE10. the issue is in $(form).submit(); in the ajaxfileupload.js file.
    IE is throwing ACCESS denied error . kindly suggest

    1. IE 9 its working fine. I have checked. IE 10 I will check from another computer. Did you go through your code and see whether you have followed the step written in this post!!

  23. Thanks For this Article its helpful but i want additional Username field in generic handler through this plugin please help

    1. Why you need to pass username field you can put that in session and access it anywhere?

    2. actually i am developing my project with jquery webservice json . There is no any aspx and aspx.cs pages

    3. Even with web service you can have session

  24. Good Script.Can you post additional data apart from the file and if so how would it be accessed in the generic handler.

    1. Nope this is a plugin so if you want to do that then you need to modify js and other stuff.

  25. Is it works for IE 8 and 9 Browser ?

    Please guide me.

    1. Yes it will work because its not using any HTML5 control.


Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog


My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews