How to Upload file in ASP.NET using jquery ajax

By FoxLearn 2/18/2024 1:17:21 AM   197
This tutorial shows you how to upload a file in ASP.NET MVC using Ajax and javascript without page refresh.

You can add a simple html layout that allows you to select a file from your hard disk, then click the upload button to upload your file to the web server.

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

Add a javascript at the bottom page as the following

<script>
$("#upload").click(function () {

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

    else {
        var fileUpload = $("#fileUpload").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        fileData.append(files[0].name, files[0]);
        $.ajax({
            url: '/home/fileupload',
            type: 'post',
            datatype: 'json',
            contentType: false,
            processData: false,
            async: false,
            data: fileData,
            success: function (response) {
                alert(response);
            }
        });
    }
});
</script>

Next, Create a upload action in your Home controller

public JsonResult FileUpload()
{
    // check your 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("Your file has been successfully uploaded.");
        }
        catch (Exception e)
        {
            return Json("error" + e.Message);
        }
    }
    return Json("Please select a file to upload !");
}

As you can see, we will call the fileupload action by using ajax