Example of jQuery File Upload in c#

Hello all,

Today i want to share you example of jQuery File Upload plugin. You can download jQuery file upload plugin from github here.

There are some example provided by them in .net also. But my requirement is not set with that so, i have prepared one example.

First include some necessary files like following.













Here you can exclude ifrmae-transport if you are not using cross domain. Also, process is used for processing and validate use to validate file.

Now, initialize the fileupload

        $(function ()
        {
            var tbodyList = "";
            var trListRowClone = "";
            'use strict';

            var url = '/Handler/Handler.ashx';
            // Initialize the jQuery File Upload widget:
            $('#fileupload').fileupload({
                url: url,
                dataType: 'text',
                autoUpload: true,
                acceptFileTypes: /(jpg)|(jpeg)|(png)|(gif)|(pdf)$/i, // Allowed file types
                progress: function (e, data)
                {
                    var bar = $('.bar');
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    var percentVal = progress + '%';
                    bar.width(percentVal);
                },
                done: function (e, data)
                {
                    var newRow = trListRowClone.cloneNode(true)
                    newRow.physicalFileName = this.files[0].name; // data
                    newRow.cells[0].getElementsByTagName("span")[0].childNodes[0].data = this.files[0].name;
                    tbodyList.appendChild(newRow);
                }
            });            
        });

Now, we write html

        
File-Name  

The Last thing is handler.


public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        
        foreach (string file in context.Request.Files)
        {
            HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile;
            string FileName = string.Empty;
            if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
            {
                string[] files = hpf.FileName.Split(new char[] { '\\' });
                FileName = files[files.Length - 1];
            }
            else
            {
                FileName = hpf.FileName;
            }
            if (hpf.ContentLength == 0)
                continue;
            
            string savedFileName = context.Server.MapPath("~/Your-folder-name/" + FileName);
            hpf.SaveAs(savedFileName);

            context.Response.Write(FileName);
            context.Response.StatusCode = 200;
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

Now, everything is ready. You can find your file at “your-folder-name”. Enjoy!!!