In this article I will explain with an example, how to upload multiple files using FormData in ASP.Net MVC.
 
 
Namespaces
You will need to import the following namespace.
using System.IO;
 
 
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation
This Action method gets called, when Upload Button is clicked.
Inside this Action method, first a check is performed whether Folder (Directory) exists, if not then the Folder (Directory) is created.
Next, the uploaded Files are read from the Request.Files collection and a loop is executed.
Inside the loop, 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 file names are returned to the Success event handler of the jQuery AJAX function.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult UploadFiles()
    {
        string message = string.Empty;
        //Create the Directory.
        string path = Server.MapPath("~/Uploads/");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        for (int i = 0; i < Request.Files.Count; i++)
        {
            //Fetch the File.
            HttpPostedFileBase postedFile = Request.Files[i];
 
            //Fetch the File Name.
            string fileName = Path.GetFileName(postedFile.FileName);
 
            //Save the File.
            postedFile.SaveAs(path + fileName);
 
            message += string.Format("<b>{0}</b> uploaded.<br />", fileName);
        }
 
        //Send OK Response to Client.
        return Content(message);
    }
}
 
 
View
The View 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.
Inside the View, 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, a jQuery AJAX call is made to the Controller’s Action method.
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.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <table>
        <tr>
            <td>Files:</td>
            <td><input type="file" id="file" multiple="multiple" /></td>
            <td><input type="button" id="btnUpload" value="Upload" /></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>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <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 () {
            var formData = new FormData();
            $.each($("#file")[0].files, function (i, file) {
                formData.append('file', file);
            });
            $.ajax({
                url: '/Home/UploadFiles',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                    $(".progress").hide();
                    $("#lblMessage").html(data);
                    $("#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>
</body>
</html>
 
 
Screenshot
Upload multiple Files using FormData in ASP.Net MVC
 
 
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