Upload a file using JQuery and Generic Handler in ASP.Net

In this blog we will learn how to use jquery and generic handler in asp.net to upload a file.
I have used Jquery to call a generic handler to upload a file.

In this blog I have written code which accepts jpg file only and file size should not exceed 10 MB.
You may customize as per your need.

So lets start by creating HTML page. Write below HTML code and Place Jquery code within script tag in head section.

Please reference a jquery library file in HTML file before proceeding.

HTML Code

<input type=”button” value=”Submit” id=”btnUpload” />
<input type=”file” name=”file” id=”file” class=”file” />

JQuery Code 

$(function () {
    $(‘#btnUpload’).click(function () {
        var msg = “”;
        var fileUpload = $(“#file”).get(0);
        var files = fileUpload.files;
        var datafile = new FormData();
        datafile.append(files[0].name, files[0]);
        var dotPosition = files[0].name.lastIndexOf(“.”);
        var fileExt = files[0].name.substring(dotPosition);
        var fileSize = Math.round(files[0].size / 1024 / 1024); //Get file size in MB
       
        if (fileExt.toLowerCase() == “.jpg” && fileSize <= 10) {
            $.ajax({
                url: “MyFileUploadHandler.ashx”,
                type: “POST”,
                contentType: false,
                processData: false,
                data: datafile,
                beforeSend: function () {
                    $(‘#btnUpload’).attr(‘value’, ‘Please Wait…’);
                },
                 
                success: function (result) {
                    
                alert(‘File Uploaded successfully’);
                $(‘#btnUpload’).attr(‘value’, ‘Submit’); //Reset button text value
                },
                error: function (err) {
                    alert(err.statusText);
                }
            });
        }
        else {
            if (fileExt.toLowerCase() != “.jpg”) {
                alert(“Wrong file format. Only .Jpg file allowed.”);
                 
            }
            else if (fileSize > 10) {
                alert(“Max. 10 MB file allowed”);
               
            }
        }
    });

})



MyFileUploadHandler.ashx


Below is the code for Generic Handler.

public void ProcessRequest (HttpContext context)
    {
        string fname = string.Empty;
        try
        {
                if (context.Request.Files.Count > 0)
                {
                    HttpFileCollection files = context.Request.Files;
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile file = files[i];
                       
                        if (HttpContext.Current.Request.Browser.Browser.ToUpper() == “IE” || HttpContext.Current.Request.Browser.Browser.ToUpper() == “INTERNETEXPLORER”)
                        {
                            string[] testfiles = file.FileName.Split(new char[] { ‘\’ });
                            fname = Guid.NewGuid() + testfiles[testfiles.Length – 1];
                            HttpContext.Current.Session[“file”] = fname;
                        }
                        else
                        {
                            fname = Guid.NewGuid() + file.FileName;
                            HttpContext.Current.Session[“file”] = fname;
                        }
                        fname = System.IO.Path.Combine(context.Server.MapPath(“~/uploads/”), fname);
                        file.SaveAs(fname);
                       
                    }
                }
                context.Response.ContentType = “text/plain”;
                context.Response.Write(“File Uploaded Successfully!”);
              
        }
        catch(Exception ex)
        {
            //Log your exception
        }
       
    }

Leave a Comment

RSS
YouTube
YouTube
Instagram