jQuery File Upload in Asp.Net C#


In this tutorial, we’ll see how to implement jQuery file upload in asp.net web application. We’ll be using a beautiful jQuery file upload plugin called blueimp.

Implementing file upload can be quite a task, if we try to implement it from scratch. But using a plugin like blueimp we really don’t need to worry about anything. It’s quite simple and can be used with any serve side platforms like PHP,Python, Ruby on Rails, Java, Go etc to name a few.

Also read : How to Implement File Upload Using AngularJS and ASP.NET MVC 4

We’ll be implementing the basic type of file upload. To get started, create a web application and add a new page called index.aspx. Here is how it looks like:

<table align="center" style="padding-top:200px;">
    <tr>
        <td>
            <input type="file" name="file" id="btnFileUpload" />
        td>
    tr>
    <tr>
        <td>
            <div id="progressbar" style="width:100px;display:none;">
                <div>
                    saadsd
                div>
            div>
        td>
    tr>
table>

Download blueimp and include the required libraries as shown below in index.aspx :

<script src="Scripts/jquery-1.11.1.js" type="text/javascript">script>
<script src="Scripts/jquery.ui.widget.js" type="text/javascript">script>
<script src="Scripts/jquery.iframe-transport.js" type="text/javascript">script>
<script src="Scripts/jquery.fileupload.js" type="text/javascript">script>

Next we’ll create a generic handler called FileUploadHandler.ashx which will handle the server side of file upload process. Here is how it looks like:

try {
    if (context.Request.QueryString["upload"] != null) {
        string pathrefer = context.Request.UrlReferrer.ToString();
        string Serverpath = HttpContext.Current.Server.MapPath("Upload");

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

        string file;

        //In case of IE
        if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE") {
            string[] files = postedFile.FileName.Split(new char[] {
                '\\'
            });
            file = files[files.Length - 1];
        } else // In case of other browsers
        {
            file = postedFile.FileName;
        }


        if (!Directory.Exists(Serverpath))
            Directory.CreateDirectory(Serverpath);

        string fileDirectory = Serverpath;
        if (context.Request.QueryString["fileName"] != null) {
            file = context.Request.QueryString["fileName"];
            if (File.Exists(fileDirectory + "\\" + file)) {
                File.Delete(fileDirectory + "\\" + file);
            }
        }

        string ext = Path.GetExtension(fileDirectory + "\\" + file);
        file = Guid.NewGuid() + ext; // Creating a unique name for the file 

        fileDirectory = Serverpath + "\\" + file;

        postedFile.SaveAs(fileDirectory);

        context.Response.AddHeader("Vary", "Accept");
        try {
            if (context.Request["HTTP_ACCEPT"].Contains("application/json"))
                context.Response.ContentType = "application/json";
            else
                context.Response.ContentType = "text/plain";
        } catch {
            context.Response.ContentType = "text/plain";
        }

        context.Response.Write("Success");
    }
} catch (Exception exp) {
    context.Response.Write(exp.Message);
}

I won’t be going into the details of the generic handler code. It’s quite self explanatory but still in case you don’t understand anything please do let me know in the comments.

Initializing the jQuery File Upload

Initializing the file upload control plugin is quite simple. After you have included the required libraries, simply call the file upload plugin as shown below:

$('#btnFileUpload').fileupload({
    url: 'FileUploadHandler.ashx?upload=start',
    add: function(e, data) {
        data.submit();
    },
    success: function(response, status) {
        // Success callback
    },
    error: function(error) {
        // Error callback
    }
});

Blueimp plugin also makes it possible to show the upload progress which is a must in case files are of large size. Tracking file upload progress is quite simple. You simply need to add another setting called progress as shown below:

$('#btnFileUpload').fileupload({
    url: 'FileUploadHandler.ashx?upload=start',
    add: function(e, data) {
        data.submit();
    },
    progress: function(e, data) {
        // Track Progress
    },
    success: function(response, status) {
        // Success callback
    },
    error: function(error) {
        // Error callback
    }
});

From the Blueimp plugin we get the total data which is to be uploaded and the data which is uploaded. So it’s easy to calculate the percentage of data uploaded. Now in order to show data upload progress graphically or as a progress bar we make use of css. As you can see we have already added a div called progressBar in our page. Next add the following css to the div :

#progressbar {
    background - color: black;
    background - repeat: repeat - x;
    border - radius: 13px;
    padding: 3px;
}

#progressbar > div {
    background - color: orange;
    width: 0 % ;
    height: 20px;
    border - radius: 10px;
}

Now modify the fileupload jQuery code as shown below to make the file upload and progress bar work:

$('#btnFileUpload').fileupload({
    url: 'FileUploadHandler.ashx?upload=start',
    add: function(e, data) {
        console.log('add', data);
        $('#progressbar').show();
        data.submit();
    },
    progress: function(e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progressbar div').css('width', progress + '%');
    },
    success: function(response, status) {
        $('#progressbar').hide();
        $('#progressbar div').css('width', '0%');
        console.log('success', response);
    },
    error: function(error) {
        $('#progressbar').hide();
        $('#progressbar div').css('width', '0%');
        console.log('error', error);
    }
});

One more important thing. In order to support upload of large files using this jQuery file upload, you’ll need to set the MaxRequestLength in the web.config

<httpRuntime  executionTimeout="6000000" maxRequestLength="2147483647" />

Now try to run the app and upload some files. jQuery file upload should be working fine and the uploaded files can be found in the Upload folder inside the web application.

Wrapping It Up

In this tutorial, we saw how to implement jQuery file upload in an ASP.NET web application. Hope you enjoyed the tutorial. Do let us know your thoughts in the comments below.

Code from the above tutorial is available on GitHub.