In this article I will explain with an example, how to upload file using
FormData and
Generic Handler (ASHX) in
ASP.Net using C# and VB.Net.
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 FormData and
XmlHttpRequest (XHR).
Adding Generic Handler
You will need to add a new Generic Handler (ASHX) file using
Add New Item Dialog of
Visual Studio as shown below.
Building the Generic Handler for uploading the Files
Inside the Generic Handler, the uploaded File is read from the Request.Files collection and the Name of the File is read from Request.Form collection along with the File extension from the GetExtension method of Path class and saved to a Folder (Directory) on Server’s Disk.
Finally, then
Name of the uploaded file is returned back to the Client in
JSON format.
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 = context.Request.Form["fileName"] + Path.GetExtension(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 = context.Request.Form("fileName") & Path.GetExtension(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:
TextBox – For inputting FileName.
FileUpload – For selecting the file.
Button – For uploading the file.
HTML5 Progress – For displaying the progress of the uploading file.
SPAN – For displaying the uploaded file details.
Uploading file to Generic Handler using FormData
Inside the
HTML Markup,
jQuery JS Script file is inherited.
1. jquery.min.js
The
Upload Button has been assigned a
jQuery Click event handler.
Inside the
Button click event handler, the File is read from the
HTML FileUpload element and the Name of the File is fetched from the
TextBox and is added to the
FormData object along with the File.
Then, an
AJAX call is made to the
Generic Handler using
jQuery and the File is uploaded using
XmlHttpRequest (XHR).
Next, a Progress event handler is attached to the XmlHttpRequest (XHR), which displays the progress of the File being uploaded using the HTML5 Progress element.
Finally, the received
Name of the uploaded File is displayed in an
HTML SPAN element.
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="fileName" /></td>
</tr>
<tr>
<td>File:</td>
<td><input type="file" id="file" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" id="btnUpload" value="Upload" /></td>
</tr>
<tr>
<td colspan="2"><progress id="fileProgress" style="display: none"></progress></td>
</tr>
</table>
<hr />
<span id="lblMessage" style="color: Green"></span>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$("body").on("click", "#btnUpload", function () {
var formData = new FormData();
formData.append("fileName", $("#fileName").val());
formData.append("file", $("#file")[0].files[0]);
$.ajax({
url: 'Handler.ashx',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (file) {
$("#fileProgress").hide();
$("#lblMessage").html("<b>" + file.name + "</b> has been uploaded.");
},
error: function (a) {
$("#lblMessage").html(a.responseText);
},
failure: function (a) {
$("#lblMessage").html(a.responseText);
},
xhr: function () {
var fileXhr = $.ajaxSettings.xhr();
if (fileXhr.upload) {
$("#fileProgress").show();
fileXhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
$("#fileProgress").attr({
value:e.loaded,
max:e.total
});
}
}, false);
}
return fileXhr;
}
});
});
</script>
Web.Config Settings for uploading Large Files
Following settings need to be add in the
Web.Config file for allow uploading files up to 2GB.
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.8"/>
<httpRuntime executionTimeout="120" maxRequestLength="2147483647"/>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648"/>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Screenshot
Downloads