Upload Image file Using jQuery Ajax in Asp.net C# [PROGRESS BAR]

 jQuery Ajax image file upload: This article explains how to upload an image file using jQuery in Asp.net C# .i.e upload an image file from client side with jQuery ajax call. This means we can upload image files without the page refresh or no postback in Asp.net C#. For this, we use Generic handler ( ashx file ) and also display progress bar while file uploading. .i.e displaying percentage while image getting uploaded.

I must suggest you to check how to preview an image before uploading it to the server with simple Jquery and HTML5 FileReader API.

Have you ever upload files without using any plugin?

If NO, then this post is about it, Asynchronous file upload using jQuery ( Ajax method ) in asp.net C# without any plugin, yes you read it right without any plugin and also display progress bar.

Let have a step by step guide

Step to Upload image using jQuery in Asp.net C#:

  1. Download and include jQuery lib file.  
  2. Add Html Markup file input tag. 
  3. Client-side: Call a jQuery Ajax method.  
  4. Server-side – Add Generic Handler (ashx file) to handle server-side code, i.e., C# code to saving the uploaded file.
  5. Show (display) Progress Bar while image uploading.

Screenshot:Upload image using jQuery ajax in Asp.net C#

# Download and include jQuery file:

Before writing any code first, we will download and add latest jQuery file. You can host the jQuery file on your server, or you can also use from the Google-hosted site.

So now our head tag looks like as written below.

//*
<script src="latestJs_1.11/jquery.min.js"></script>
//*

# HTML Markup:

Here now we add a file input tag (file upload control ), and an image tag.

Browse control to select the image file, and when the image gets uploaded will set the newly uploaded image path/source to our image control, which we have already added on our Asp.net Web Page.

Finally, this is how our HTML looks like as written below.

//*
<input type="file" class="upload"  id="f_UploadImage"><br />
<img id="myUploadedImg" alt="Photo" style="width:180px;" />
//*

# jQuery: Calling  jQuery AJAX method

Now we create a common function sendFile() in which we add the file content to FormData’s collection and making a jQuery Ajax call

//*
function sendFile(file) {
            
    var formData = new FormData();
    formData.append('file', $('#f_UploadImage')[0].files[0]);
    $.ajax({
        type: 'post',
        url: 'fileUploader.ashx',
        data: formData,
        success: function (status) {
            if (status != 'error') {
                var my_path = "MediaUploader/" + status;
                $("#myUploadedImg").attr("src", my_path);
            }
        },
        processData: false,
        contentType: false,
        error: function () {
            alert("Whoops something went wrong!");
        }
    });
}
//*

 Note: The contentType and processData are set to false which is important.

Now we call this function on File Upload control change event. .i.e. whenever user select any image file to upload our sendFile() function gets call. Code as shown below.

//*
var _URL = window.URL || window.webkitURL;
$("#f_UploadImage").on('change', function () {

    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            sendFile(file);
        };
        img.onerror = function () {
            alert("Not a valid file:" + file.type);
        };
        img.src = _URL.createObjectURL(file);
    }
});
//*

You may have notice in above jQuery ajax method we set URL as fileUploader.ashx this is Generic Handler (ashx file). By using this file, we will upload files on the server side.  We are done with our client-side code, let’s head to server-side code 🙂

# Server-side: Add Generic Handler ( ashx file) to handle server side code i.e. C# code to save image file on the server.

Now first import System.IO namespaces as shown in below code.

//*
using System.IO;
//*

Copy the below-written code, this will get the files from client-side, and rename image with a unique name, then save it to the MediaUploader folder.

//*
using System;
using System.Web;
using System.IO;
public class fileUploader : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        try
        {
            string dirFullPath = HttpContext.Current.Server.MapPath("~/MediaUploader/");
            string[] files;
            int numFiles;
            files = System.IO.Directory.GetFiles(dirFullPath);
            numFiles = files.Length;
            numFiles = numFiles + 1;
            string str_image = "";

            foreach (string s in context.Request.Files)
            {
                HttpPostedFile file = context.Request.Files[s];
                string fileName = file.FileName;
                string fileExtension = file.ContentType;

                if (!string.IsNullOrEmpty(fileName))
                {
                    fileExtension = Path.GetExtension(fileName);
                    str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
                    string pathToSave_100 = HttpContext.Current.Server.MapPath("~/MediaUploader/") + str_image;
                    file.SaveAs(pathToSave_100);
                }
            }
            //  database record update logic here  ()
            
            context.Response.Write(str_image);
        }
        catch (Exception ac) 
        { 
        
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}
//*

Note: Here MediaUploader is our folder name, where all our uploaded images get saved.

  Output: Finally we are done with Uploading image using jQuery ajax Upload image using jQuery ajax in Asp.net C#


#BONUS: How to Show progress bar / Loading percentage value while uploading file with jQuery Ajax in Asp.net C#

It’s a good user experience to display uploading percentage or to display the progress bar while uploading files using jquery ajax. For this, we have to add a div tag where we set percentage value of uploading files and with Custom XMLHttpRequest we get for percentage values. Here’s how the code looks like for jquery ajax progress bar.

Html Markup:

<div id="#statustxt">0%</div>

jQuery Code: Below function set the values on the progress bar.


function progressHandlingFunction(e)
{
 if(e.lengthComputable){
 var percentage = Math.floor((e.loaded / e.total) * 100);
 //update progressbar percent complete
 statustxt.html(percentage + '%');
 console.log("Value = "+e.loaded +" :: Max ="+e.total);
 }
}

Now we see how to use this function in our jquery ajax. In short, we have to modify our sendFile() function which we have written above in this article. Code look like this


function sendFile(file) {
            
    var formData = new FormData();
    formData.append('file', $('#f_UploadImage')[0].files[0]);
    $.ajax({
        type: 'post',
        url: 'fileUploader.ashx',
        data: formData,
        xhr: function() {  // Custom XMLHttpRequest
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ // Check if upload property exists
                     //update progressbar percent complete
                     statustxt.html('0%');
             	     // For handling the progress of the upload
             	     myXhr.upload.addEventListener('progress',progressHandlingFunction, false);

                   }
                   return myXhr;
                }
        success: function (status) {
            if (status != 'error') {
                var my_path = "MediaUploader/" + status;
                $("#myUploadedImg").attr("src", my_path);
            }
        },
        processData: false,
        contentType: false,
        error: function () {
            alert("Whoops something went wrong!");
        }
    });
}

Now we are done with File Upload using jquery ajax with Progress bar .i.e displaying percentage on file (Image) upload.

You can also check these articles:

  1. An easy way to upload bulk images in Asp.net C#.
  2. Upload and Resize an image using Dropzone Js in Asp.net.
  3. Preview Image before uploading it with jQuery in Asp.net.
  4. Generic Handler ashx file: Post send JSON data in Asp.net C#.
  5. jQuery Ajax JSON Example in Asp.net with SQL database.

Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!

Share:    
Satinder Singh

Hi all, am Founder and Author of Codepedia.info, also atypical polyglot programmer from Bombay, India. I have a passion to create, solve, and deploy software applications.
       ForEach ( minute in MyLife ) { myExperience++ ; }


34 comments on “Upload Image file Using jQuery Ajax in Asp.net C# [PROGRESS BAR]”

  1. Rohit

    Hello Sir,
    First thank for your article,
    but there is an error when i an adding the progress bar code in it.
    it does not go to server side code and send error.
    it goes to javascript error

  2. Gerardo

    muchas gracias!!
    estupenda enseñanza,
    para los que no les toma el nombre del archivo en IE agreguen Path.GetFileName().

  3. Partha Roy

    I trying for the last 8 hours to get this working. I keep on getting these 404.5, 404.3 and now 405 errors. It seems some web.config changes are also needed for the mime, http verb settings. Could you please post the complete thing.

    • Satinder singh

      Hi partha,
      The above error is not related to this code, it seem your IIS it not config properly. Let me know are you available to upload image with jquery ajax in your local machine with VS ?

  4. Lucas Marçoni

    Excelent! It works for me!!! Thank you dude!!!
    The generic handler was essential in my case… I tried to call a web method of my ASPX page but it was not possible because the HttpContext context parameter and because the option with false on the ajax call.

    • Satinder singh

      Hi tiru,
      You are getting “Whoops something went wrong!” alert message, because you have set this as default error message on jquery ajax error method. If you want to check the exact error with code you have make change in your error method as something like this
      error: function (response) {
      console.log(response);
      }

  5. Siddihant

    Hello,

    I have read all code and used in my application. i am running my project through Chrome. My image is uploaded but image is not displayed.

    In my publish ImageStorage is for uploaded image all images saved in that folder and it works.

    But image is not displayed following error appears when i inspect particular page Chrome
    it gives error like: http://localhost:2317/Zelia/Main_Masters/ImageStorage/Tulips.jpg Failed to load resource: the server responded with a status of 404 (Not Found)

    How to resolve this problme

    Thanks,
    Siddhnat

  6. Himanshu Jain

    BIG THANKS.. YOUR SOLUTION WORKS .. WAS A SUBERB QUICK HELP !!

    KEEP SHARING COOL STUFFS LIKE THIS !!

    • Satinder singh

      Hi Himanshu Jain,
      Thanks for reading it, and yes you can upload any format file using jquery ajax in asp.net. All you need to do little tweak the above-given code i.e by removing the validation of image format check

  7. vishal Mahajan

    If i upload the Image using this Code But After refresh the Page Image Does Not Display Please Provide Me Code After Uploading the Image if i Refresh the Page It could not be removed. How I can bind the Image if i have One Time Upload the image

    • Satinder singh

      Hello Vishal thanks for reading.
      Above code is about how to upload image files using jquery ajax. If you want to display image on page refresh / page load you can do it by adding an asp.net image control on your .aspx page, and from code-behind set image src

    • Satinder singh

      Hi preeti singh,
      To save an image in your project file, you need to make an ajax call, which have shown in this article. Pls follow step by step process. All you need to edit your ProjectFolder name inside your Generic Handler file (fileUploader.ashx)

  8. tusto

    What if I want to associate these photos to a profile record, which profile ID will be available after I click the insert button?

    • Satinder singh

      Hi tusto,
      Using session value on server-side you can easily link these uploaded photos with respected User/ Profile ID. i.e you can save and access session value in your generic handler

    • Satinder singh

      @sandesh Chavan: Yeah it won’t work in IE 8, bcoz FormData() is only supported from IE10, that;s the reason why many developer hate IE.
      There are many jQuery plugins availabe, by using it you can upload image in IE also

      • Deepak karma

        Yes. you are right. IE is still looks outdated even IE 10 IE 11 has come.I am one of the developer also Hate this IE.Microsoft should shakehand with google for chrome as default browser. 😛


Post Comment


Your email address will not be published. Required fields are marked *