In this article I will explain with an example, how to upload multiple files using FormData in ASP.Net using C# and VB.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 multiple Files using FormData in ASP.Net
 
 
Building the Generic Handler for Uploading the Files
Inside the Generic Handler, first the uploaded File is read from the Request.Files collection and a loop is executed
Inside the loop, a check is performed whether Folder (Directory) exists, if not then the Folder (Directory) is created.
Then, the Name of the Files are read from the GetFileName property of the HttpPostedFile and saved to a Folder (Directory) on Server’s Disk.
Finally, the Name of the uploaded files are returned back to the Client in JSON format.
C#
<%@WebHandler Language="C#" Class="Handler" %>
 
using System;
using System.Web;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;
 
public class Handler : IHttpHandler
{
 
    public void ProcessRequest(HttpContext context)
    {
        string message = string.Empty;
 
        for (int i = 0; i < context.Request.Files.Count; i++)
        {
            //Fetch the Uploaded File.
            HttpPostedFile postedFile = context.Request.Files[i];
 
            //Fetch the File Name.
            string fileName = Path.GetFileName(postedFile.FileName);
 
            //Set the Folder Path.
            string folderPath = context.Server.MapPath("~/Uploads/");
 
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
 
            //Save the File in Folder.
            postedFile.SaveAs(folderPath + fileName);
 
            message += string.Format("<b>{0}</b> uploaded.<br />", fileName);
        }
        //Send File details in a JSON Response.
        string json = new JavaScriptSerializer().Serialize(
            new
            {
                name = message
            });
        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.Web
Imports System.Net
Imports System.IO
Imports System.Web.Script.Serialization
 
Public Class Handler : Implements IHttpHandler
 
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim message As String = String.Empty
        For i As Integer = 0 To context.Request.Files.Count - 1
            'Fetch the Uploaded File.
            Dim postedFile As HttpPostedFile = context.Request.Files(i)
 
            'Fetch the File Name.
            Dim fileName As String = Path.GetFileName(postedFile.FileName)
 
            'Set the Folder Path.
            Dim folderPath As String = context.Server.MapPath("~/Uploads/")
 
            If Not Directory.Exists(folderPath) Then
                Directory.CreateDirectory(folderPath)
            End If
 
            'Save the File in Folder.
            postedFile.SaveAs(folderPath & fileName)
            message += String.Format("<b>{0}</b> uploaded.<br />", fileName)
        Next
        'Send File details in a JSON Response.
        Dim json As String = New JavaScriptSerializer().Serialize(
            New With {Key .name = message})
        context.Response.StatusCode = CInt(HttpStatusCode.OK)
        context.Response.ContentType = "text/json"
        context.Response.Write(json)
        context.Response.End()
    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:
FileUpload – For selecting the file.
Button – For uploading the file.
DIV – For displaying the progress bar.
SPAN – For displaying the uploaded file details.
HTML FileUpload element is set with multiple attribute, which allow user to select multiple files.
<table>
    <tr>
        <td>Files:</td>
        <td>
            <input type="file" id="file" multiple="multiple" /></td>
        <td><input type="button" id="btnUpload" value="Upload" onclick="UploadFiles" /></td>
    </tr>
    <tr>
        <td colspan="3">
            <div class="progress" style="display: none">
                <div class="progress-bar" role="progressbar"></div>
            </div>
        </td>
    </tr>
</table>
<hr/>
<span id="lblMessage" style="color: Green"></span>
 
 
Uploading file to Generic Handler using FormData
Inside the HTML Markup, the Bootstrap CSS file is inherited.
1. bootstrap.min.css
Then, the jQuery JS Script file is inherited.
1. jquery.min.js
The Upload Button has been assigned a jQuery Click event handler.
Inside this click event handler, a loop is executed over the uploaded files and each file added to an HTML5 FormData JavaScript object and then the File is uploaded using XmlHttpRequest (XHR).
Then, an AJAX call is made to the Generic Handler using jQuery.
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 Name of the uploaded files are displayed in an HTML SPAN element.
<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 () {
        var formData = new FormData();
        $.each($("#file")[0].files, function (i, file) {
            formData.append('file', file);
        });
        $.ajax({
            url: 'Handler.ashx',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function (file) {
                $(".progress").hide();
                $("#lblMessage").html(file.name);
                $("#file").val("");
                $('.progress-bar').text('0%');
                $('.progress-bar').width('0%');
            },
            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>
 
 
Screenshot
Upload multiple Files using FormData 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