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