ASP.NET Multiple File Upload with Progress Bar

ASP.NET Multiple File Upload with Progress Bar

In this tutorial I will show how to create ASP.NET File Upload with Progress Bar. It can do Multiple File Upload at the same time and show the real time progress of upload with just a few lines of JavaScript.

Here I will use XMLHttpRequest for making Ajax request when uploading the files to the server. This will not do the page postback either. I will also use 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

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

public class fileuploadhandler : IHttpHandler {
    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 the ‘uploads’ folder which is in the root of the website. Therefore create an empty folder in the website root and name it ‘uploads’.

In the end, after the file is uploaded, the generic handler returns the message ‘File Uploaded Successfully!’

I can also apply validations to the HTML controls using jQuery. For this check the tutorial on jQuery 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’. I 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 –

<asp:FileUpload ID="file1" runat="server" AllowMultiple="true" /><br>
<input type="button" value="Upload File" onclick="UploadFile()" />
<progress id="progressBar" value="0" max="100" style="width: 300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>

On button click I are calling the JavaScript function ‘UploadFile()’

AJAX File Upload

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

<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 handler ‘fileuploadhandler’ one by one until all the files are uploaded successfully.

I have added ‘Events’ – progress, load, error, abort which calls the respective JavaScript functions to update the progress bar in real time.

In this way you 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.