Upload files with Percentage Progress Bar using C# and VB.Net in ASP.Net

ashish007
 
on Jul 18, 2020 10:00 PM
Sample_804912.zip
3205 Views

File upload with Percentage progress bar c# in asp.net

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 20, 2020 05:35 AM

Hi ashish007,

Refer below sample code.

HTML

<input type="file" name="postedFile" />
<input type="button" id="btnUpload" value="Upload" />
<hr />
<div class="progress" style="display: none">
    <div class="progress-bar" role="progressbar"></div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript">
    $("body").on("click", "#btnUpload", function () {
        $.ajax({
            url: 'Handler.ashx',
            type: 'POST',
            data: new FormData($('form')[0]),
            cache: false,
            contentType: false,
            processData: false,
            success: function (file) {
            },
            xhr: function () {
                var fileXhr = $.ajaxSettings.xhr();
                if (fileXhr.upload) {
                    $(".progress").show();
                    fileXhr.upload.addEventListener("progress", function (e) {
                        if (e.lengthComputable) {
                            var percentage = ((e.loaded / e.total) * 100).toFixed(2);
                            $('.progress-bar').text(percentage + '%');
                            $('.progress-bar').width(percentage + '%');
                            if (percentage == 100) {
                                $('.progress-bar').text('Upload Completed');
                            }
                        }
                    }, false);
                }
                return fileXhr;
            }
        });
    });
</script>

Handler

C#

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

public class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //Check if Request is to Upload the File.
        if (context.Request.Files.Count > 0)
        {
            //Fetch the Uploaded File.
            HttpPostedFile postedFile = context.Request.Files[0];

            //Set the Folder Path.
            string folderPath = context.Server.MapPath("~/Uploads/");

            //Set the File Name.
            string fileName = Path.GetFileName(postedFile.FileName);

            //Save the File in Folder.
            postedFile.SaveAs(folderPath + fileName);

            //Send File details in a JSON Response.
            string json = new JavaScriptSerializer().Serialize(new { name = fileName });
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            context.Response.ContentType = "text/json";
            context.Response.Write(json);
            context.Response.End();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

VB.Net

<%@ WebHandler Language="VB" Class="Handler" %>

Imports System
Imports System.IO
Imports System.Net
Imports System.Web
Imports System.Web.Script.Serialization

Public Class Handler : Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        'Check if Request is to Upload the File.
        If context.Request.Files.Count > 0 Then

            'Fetch the Uploaded File.
            Dim postedFile As HttpPostedFile = context.Request.Files(0)

            'Set the Folder Path.
            Dim folderPath As String = context.Server.MapPath("~/Uploads/")

            'Set the File Name.
            Dim fileName As String = Path.GetFileName(postedFile.FileName)

            'Save the File in Folder.
            postedFile.SaveAs(folderPath + fileName)

            'Send File details in a JSON Response.
            Dim json As String = New JavaScriptSerializer().Serialize(New With {.name = fileName})
            context.Response.StatusCode = CInt(HttpStatusCode.OK)
            context.Response.ContentType = "text/json"
            context.Response.Write(json)
            context.Response.End()
        End If
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class