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

Introduction


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

Front-End


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]);

        $.ajax({
            url: '/Test/uploadFile',
            type: 'post',
            datatype: 'json',
            contentType: false,
            processData: false,
            async: false,
            data: fileData,
            success: function (response) {
                alert(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.

Back-End


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

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

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

            // save the file
            file.SaveAs(path);
            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.


Namespace


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

using System.IO;