In this article I will explain with an example, how to upload file using jQuery AJAX in ASP.Net MVC.
 
 
Namespaces
You will need to import the following namespace.
using System.IO;
 
 
Controller
The Controller consists of following two 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 is executed when the Upload button is clicked.
Inside this Action method, first a check is performed whether Directory (Folder) exists, if not then the Directory (Folder) is created.
Then, the Name of the File is read from Request.Form collection and the File is read from the Request.Form.Files collection and saved in the Directory (Folder).
Finally, the FileName is sent to the Client using Content function.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult UploadFiles()
    {
        //Create the Directory.
        string path = Server.MapPath("~/Uploads/");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        //Fetch the File.
        HttpPostedFileBase postedFile = Request.Files[0];
 
        //Fetch the File Name.
        string fileName = Request.Form["fileName"] + Path.GetExtension(postedFile.FileName);
 
        //Save the File.
        postedFile.SaveAs(path + fileName);
 
        //Send OK Response to Client.
        return Content(fileName);
    }
}
 
 
View
The View consists of an HTML Table.
The HTML Table consists of an HTML TextBox, an HTML FileUpload element, a Button and an HTML5 Progress element for displaying the progress of the uploading File and an HTML SPAN element.
The Upload Button has been assigned a jQuery Click event handler.
When the Upload Button is clicked, the Name of the File is fetched from the TextBox and is added to a HTML5 FormData object.
Then, the File is read from the HTML FileUpload element and added to the HTML5 FormData object and then 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 HTML5 Progress element.
Finally, the received Name of the uploaded File is 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>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/1.8.3/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: '/Home/UploadFiles',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (fileName) {
                    $("#fileProgress").hide();
                    $("#lblMessage").html("<b>" + fileName + "</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>
</body>
</html>
 
 
Screenshot
Upload file using jQuery AJAX 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