ASP.NET Multiple File Upload with Progress Bar

ASP.NET Multiple File Upload with Progress Bar

In this tutorial we will show how to create ASP.NET File Upload with Progress Bar. It can do Mulitple File Upload at the same time and show the real time progress of upload with just a few lines of JavaScript. Here we will use ‘XMLHttpRequest ‘ for making Ajax request when uploading the files to the server, without doing a page postback. We will also need a ‘Generic Handler’ which will be called from JavaScript code and whose work will be to upload the files to the server.

Multiple File Upload

First Create a Generic Handler which is the first step in creating Multiple File Upload. It will be called by the JavaScript Code. Below is the code of the Generic Handler.

public void ProcessRequest(HttpContext context)
{
    HttpPostedFile file = context.Request.Files[0];
    string fname = context.Server.MapPath("~/uploads/" + file.FileName);
    file.SaveAs(fname);
    context.Response.ContentType = "text/plain";
    context.Response.Write("File Uploaded Successfully!");
}

public bool IsReusable
{
    get
    {
        return false;
    }
}

Note that the generic handler uploads files to ‘uploads’ folder in the root of our website. Therefore create an empty folder in the website root and give it the name ‘uploads’. In the end, after the file is uploaded, the generic handler returns the message ‘File Uploaded Successfully!’

We can also apply validations to the HTML controls using jQuery. For this check our tutorial – jQuery Form Validation which explains how to validate controls like dropdown, checkbox, radio button & more on the button click event.

Asp.Net Progress Bar

Now create a web form and give it name ‘fileupload.aspx’. We will use Asp.Net Progress Bar control whose work will be to show the real time status (like how many files are uploaded, what % of the file is currently uploaded, etc). Add the following html code to it –

<h1>Multi File Upload With Progress Bar</h1>
<input type="button" value="Upload File" /> <progress id="progressBar" style="width: 300px;" value="0" max="100"></progress>
<h3 id="status"></h3>

On button click we are calling the Javascript function ‘UploadFile()’

AJAX File Upload

Our files will be uploaded through AJAX therefore we will need few lines of JavaScript which will make the AJAX request. Add the following Javascript code to our web page:

<script src="JS/jquery.min.js"></script>
<script>
    var counter;
    function UploadFile() {
        var files = $("#<%=file1.ClientID%>").get(0).files;
        counter = 0;

        // Loop through files
        for (var i = 0; i < files.length ; i++) {
            var file = files[i];
            var formdata = new FormData();
            formdata.append("file1", file);
            var ajax = new XMLHttpRequest();
	
            ajax.upload.addEventListener("progress", progressHandler, false);
            ajax.addEventListener("load", completeHandler, false);
            ajax.addEventListener("error", errorHandler, false);
            ajax.addEventListener("abort", abortHandler, false);
            ajax.open("POST", "FileUploadHandler.ashx");
            ajax.send(formdata);
        }
    }
    function progressHandler(event) {
        $("#loaded_n_total").html("Uploaded " + event.loaded + " bytes of " + event.total);
        var percent = (event.loaded / event.total) * 100;
        $("#progressBar").val(Math.round(percent));
        $("#status").html(Math.round(percent) + "% uploaded... please wait");
    }
    function completeHandler(event) {
        counter++
        $("#status").html(counter + " " + event.target.responseText);
    }
    function errorHandler(event) {
        $("#status").html("Upload Failed");
    } function abortHandler(event) {
        $("#status").html("Upload Aborted");
    }
</script>

Explanation – The function ‘UploadFile’ is called on button click. It loops to all the files of the file upload control, makes AJAX request using ‘XMLHttpRequest’ to the generic hander ‘FileUploadHandler’ one by one until all the files are uploaded successfully. We have added ‘Events’ – progress, load, error, abort which calls the respective Javascript functions to update the progress bar in real time.

In this way we can create ASP.NET File Upload which can upload multiple files and shows file upload progress too. It will provide high quality user experience in our website.

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.