How to upload a file in ASP.NET MVC using javascript (jquery) and ajax


In this tutorial, i will show you how to upload a file in ASP.NET MVC using JavaScript (JQuery) and AJAX.


First of all you will need a file input tag and a button to trigger the upload.

<input type="file" id="fileToUpload" class="form-control" /> <br /> 
<button id="upload" class="btn btn-primary">Upload</button>

We will use the FormData object to send the file to the server. for more information about the FormData object see this entry

$("#upload").click(function () {

    if (window.FormData == undefined)
        alert("Error: FormData is undefined");

    else {
        var fileUpload = $("#fileToUpload").get(0);
        var files = fileUpload.files;

        var fileData = new FormData();

        fileData.append(files[0].name, files[0]);

            url: '/Test/uploadFile',
            type: 'post',
            datatype: 'json',
            contentType: false,
            processData: false,
            async: false,
            data: fileData,
            success: function (response) {


In preceding code, we check if the window.FormData is defined in our browser. Then we create a new FormData object and we append the injected file to upload. After that, we use an AJAX call to send the uploaded file to the server side.


public JsonResult uploadFile()
    // check if the user selected a file to upload
    if (Request.Files.Count > 0)
            HttpFileCollectionBase files = Request.Files;

            HttpPostedFileBase file = files[0];
            string fileName = file.FileName;

            // create the uploads folder if it doesn't exist
            string path = Path.Combine(Server.MapPath("~/uploads/"), fileName);

            // save the file
            return Json("File uploaded successfully");

        catch (Exception e)
            return Json("error" + e.Message);

    return Json("no files were selected !");

In preceding code, we check the number of files sent by the user to see if he actually uploaded a file or not. After that, we put the first file in the HttpPostedFileBase object. The CreateDirectory method creates the folder (if it doesn't exist) where we want to save the uploaded file. The SaveAs method saves the file in the given path.


to work with the different IO objects used in this tutorial, you have to include this namespace :

using System.IO;