The
Generic Handler will be will be called using
jQuery AJAX and the file will be uploaded to Folder (Directory) with Progress Bar using
HTML5 Form Data and
XmlHttpRequest (XHR).
Adding Generic Handler
Building the Generic Handler for uploading the Files
The uploaded File is read from the Request.Files collection and is saved to a Folder (Directory) on Server’s Disk.
Then
Name of the uploaded file is returned back to the Client in
JSON format.
C#
<%@ WebHandler Language="C#" Class="HandlerCS" %>
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
public class HandlerCS : 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="HandlerVB" %>
Imports System
Imports System.IO
Imports System.Net
Imports System.Web
Imports System.Web.Script.Serialization
Public Class HandlerVB : 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
HTML Markup
The
HTML Markup consists of a Form with an
HTML FileUpload element and a Button. Below the Form there is a
Bootstrap Progress Bar for displaying the progress of the uploading File with percentage.
The
Upload Button has been assigned a
jQuery Click event handler. When the
Upload button is clicked, an
AJAX call is made to the
Generic Handler using
jQuery.
The data of the selected File is read into an
HTML5 FormData JavaScript object and the File is uploaded using
XmlHttpRequest (XHR).
A Progress event handler is attached to the XmlHttpRequest (XHR), which displays the progress of the File being uploaded using the Bootstrap Progress Bar with percentage.
Finally, the received
Name of the uploaded File is displayed in an
HTML SPAN element.
<form id="form1" runat="server">
<input type="file" name="postedFile" /><input type="button" id="btnUpload" value="Upload" />
<div class="progress" style="display:none">
<div class="progress-bar" role="progressbar"></div>
</div>
<div id="lblMessage" style="color:Green"></div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/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: 'HandlerCS.ashx',
type: 'POST',
data: new FormData($('form')[0]),
cache: false,
contentType: false,
processData :false,
success: function (file) {
setTimeout(function () {
$(".progress").hide();
$("#lblMessage").html("<b>" + file.name + "</b> has been uploaded.");
}, 1000);
},
error:function (a) {
$("#lblMessage").html(a.responseText);
},
failure:function (a) {
$("#lblMessage").html(a.responseText);
},
xhr:function () {
var fileXhr = $.ajaxSettings.xhr();
if (fileXhr.upload) {
$(".progress").show();
fileXhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
var percentage = Math.ceil(((e.loaded /e.total) * 100));
$('.progress-bar').text(percentage + '%');
$('.progress-bar').width(percentage + '%');
if (percentage == 100) {
$('.progress-bar').text('100%');
}
}
}, false);
}
return fileXhr;
}
});
});
</script>
</form>
Web.Config Settings for uploading Large Files
Below is the
Web.Config configuration for uploading files upto 2GB.
<configuration>
<system.web>
<compilation debug= "true" targetFramework= "4.8.1"/>
<httpRuntime executionTimeout= "120" maxRequestLength= "2147483647"/>
<pages controlRenderingCompatibilityVersion= "4.0"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength= "2147483648"/>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads