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

/ / 39 Comments

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 a generic handler ( ashx file ) and also display a progress bar while file uploading. .i.e displaying percentage while image gets uploaded.

I must suggest you to check how to preview an image before upload it to the server using 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 the progress bar.

Let have a step by step guide

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

  1. Download and include the 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:

# Download and include jQuery file:

Before writing any code first, we will download and add the latest jQuery file. You can host the jQuery file on your server, or you can also use 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 a 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 noticed in the above jQuery ajax method we set the 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 the image file on the server.

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

//*
using System.IO;
//*

Copy the below-written code, this will get the files from the client-side, and rename the 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 images using jQuery Ajax

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

It's a good user experience to display the uploading percentage or to display the progress bar while uploading files. This indicates to the user that something is processing in the background .i.e file uploading is in process in the background.

For this, we have to add a div tag where we set the percentage value of uploading files and with Custom XMLHttpRequest we get for percentage values.

Here's how the code looks like for the jQuery ajax progress bar.

Html Markup:

<div id="#statustxt">0%</div>
jQuery Code: Below function sets 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 looks 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.
  6. jQuery ajax file upload in ASP.NET CORE.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

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

39 Comments

  1. Sandesh Chavan 06/27/2015 08:34:18
    function sendFile(file) { var formData = new FormData(); FormData is not supported in IE 8
  2. Deepak karma 01/18/2016 12:31:11
    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. :P
  3. tusto 02/24/2016 14:59:25
    What if I want to associate these photos to a profile record, which profile ID will be available after I click the insert button?
  4. Taha 02/29/2016 15:22:53
    It was very clear and simple but pro example. Thanks to share
  5. Satinder singh 03/01/2016 15:42:17
    Hi Taha, Thanks for the reading, keep visiting for some more awesome future article :)
  6. Satinder singh 03/01/2016 15:47:39
    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
  7. preeti singh 04/14/2016 05:37:06
    i have an html file upload control] how to save file to to my project folder using jquery
  8. Satinder singh 04/14/2016 07:20:42
    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)
  9. yellareddy 04/20/2016 11:50:14
    thank you very much satinder singh for writing such a imporpant code,in my project it is very useful
  10. Satinder singh 04/20/2016 15:33:27
    Glad it was helpful! Thanks for reading, yellareddy :)
  11. vishal Mahajan 05/05/2016 05:52:23
    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
  12. Satinder singh 05/05/2016 06:19:04
    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
  13. Himanshu Jain 05/25/2016 15:24:22
    Hi I am looking to upload .pdf along with image files. Is that possible ?
  14. Satinder singh 05/25/2016 16:04:55
    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
  15. Himanshu Jain 05/25/2016 20:48:41
    BIG THANKS.. YOUR SOLUTION WORKS .. WAS A SUBERB QUICK HELP !! KEEP SHARING COOL STUFFS LIKE THIS !!
  16. gopinath 07/15/2016 08:18:32
    Where to call that senfile() function???pls help me
  17. Satinder singh 07/15/2016 10:45:18
    You can call sendfile funciton onchange event of your input file control
  18. Siddihant 07/16/2016 10:06:37
    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
  19. Siddihant 07/16/2016 10:08:31
    actually scource is missing
  20. Tiru riru 10/19/2016 07:31:45
    all I get is Whoops something went wrong!""
  21. JD2995 11/24/2016 22:14:28
    Thank you, man!
  22. Lucas Marçoni 11/29/2016 19:09:10
    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.
  23. Partha Roy 12/15/2016 12:13:12
    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.
  24. Satinder singh 12/18/2016 17:59:01
    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 ?
  25. Miller 01/06/2017 09:40:16
    Thanks, its working for me... Could you tell me how to add a process bar ?
  26. Satinder singh 01/06/2017 17:15:36
    Hi Miller, I have updated this in my article, i.e using custom XMLHttpRequest we can display progress bar while uploading image using jquery ajax
  27. harris 02/14/2017 05:55:55
    great job dude! but how can i convert this for Movie file .May you kindly tell me
  28. Gerardo 03/07/2017 17:11:40
    muchas gracias!! estupenda enseñanza, para los que no les toma el nombre del archivo en IE agreguen Path.GetFileName().
  29. Rohit 03/21/2017 07:44:16
    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
  30. Satinder singh 04/06/2017 15:16:30
    Hi Rohit, Pls let me know what error are you getting ?
  31. ss 04/14/2017 11:09:59
    Anjellina jolly photo for preview image in jquery
  32. Satinder singh 05/22/2017 16:39:20
    Yes i like her :)
  33. Din 01/25/2018 18:32:17
    Hey! you did a great job in this article I want to know why FileUploader is not able to upload other files such as DOCS, PDF, XLSX. I Tried but this breaks at following line HttpPostedFile file = context.Request.Files[s];
  34. Satinder singh 05/09/2018 20:00:12
    Hi din, You can upload any file format, here just for this article i uploaded image format.
  35. Waqas 06/09/2018 20:59:21
    Sir please solve my problem i m saving data in database with jquery ajax in asp.net there are my fields name gender salary and employee image image save with data field only save path in database and image save in predefine folder how is possible please help me with example thankyou
  36. Mehmet 08/31/2018 13:22:44
    hello i need a sample that saves images to a mssql by using javascript (jquery) and .net webservices (html or aspx)
  37. Avak 05/29/2021 03:07:23
    Hi, I have tried your "How to preview image before upload using jQuery - FileReader()" and it works well. However when I tried your "Upload Image file Using jQuery Ajax in Asp.net C# [PROGRESS BAR]" it does not work. I am using VS 2019 Pro subscription. Do you have a chance to send me demo codes similar to what you have provided for the "How to Preview...." ? Thank you.
  38. Satinder Singh 05/30/2021 13:32:39
    Hi Avak, I have written this article very long back using webforms. So it hard to find this code repository. Well, you can share the error here, what exact error msg comes on debug.
  39. Maurilio Maruccio 04/10/2022 07:31:55
    The solution is fantastic and avoids the problem of postback management using classic update panel in file upload management