JavaScript MVC

MVC FileUpload Ajax Post

http://dotnet-tutorials.net/Article/upload-file-ASP-NET-MVC-javascript-ajax

<input type="file" id="fileToUpload" class="form-control" /> <br />  <button id="upload" class="btn btn-primary">Upload</button>
$("#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);
            }
        });
    }

});
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 !");
}