In this article I will explain with an example, how to upload File and JSON data in same POST request using jQuery AJAX in ASP.Net with C# and VB.Net.
The File and additional data will be uploaded using FormData, JSON and jQuery AJAX in ASP.Net.
 
 
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.
Upload File and JSON data in same POST request using jQuery AJAX in ASP.Net
 
 
Building the Generic Handler for uploading the Files
Inside the Generic Handler, the uploaded File is read from the Request.Files collection while the name of the File is fetched from the Request.Form collection using the name of the HTML Input TextBox.
Then the File is saved to a Folder (Directory) on Server’s Disk as per the fetched name of the File.
Finally, the 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];
           
            //Fetch the File Name.
            string fileName = context.Request.Form["fileName"];
 
            //Set the Folder Path.
            string folderPath = context.Server.MapPath("~/Uploads/");
 
            //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)
           
            'Fetch the File Name.
            Dim fileName As String = context.Request.Form("fileName")
 
            'Set the Folder Path.
            Dim folderPath As String = context.Server.MapPath("~/Uploads/")
 
            '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, HTML Input TextBox and a Button. Below the Form there’s an HTML5 Progress element for displaying the progress of the uploading File.
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 from FileUpload and the name of the File from the TextBox are read into an HTML5 FormData JavaScript object and the File along with the additional Data 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 HTML5 Progress element.
Finally, the received Name of the uploaded File is displayed in an HTML SPAN element.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>File:</td>
            <td><input type="file" name="postedFile" /></td>
        </tr>
        <tr>
            <td>Name: </td>
            <td><input type="text" name="fileName" /></td>
        </tr>
    </table>
    <progress id="fileProgress" style="display: none"></progress>
    <hr />
    <span id="lblMessage" style="color: Green"></span>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <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) {
                    $("#fileProgress").hide();
                    $("#lblMessage").html("<b>" + file.name + "</b> has been uploaded.");
                },
                xhr: function () {
                    var fileXhr = $.ajaxSettings.xhr();
                    if (fileXhr.upload) {
                        $("progress").show();
                        fileXhr.upload.addEventListener("progress", function (e) {
                            if (e.lengthComputable) {
                                $("#fileProgress").attr({
                                    value: e.loaded,
                                    max: e.total
                                });
                            }
                        }, false);
                    }
                    return fileXhr;
                }
            });
        });
    </script>
    </form>
</body>
</html>
 
 
Screenshot
Upload File and JSON data in same POST request using jQuery AJAX in ASP.Net
 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.
Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads