Sunday, August 18, 2019

How to Upload Multiple files using jQuery AJAX in ASP.NET MVC

First create the 3 controls on your View

1
2
3
<input type="file" id="fileInput" multiple />
<input type="button" id="fileButton" value="Upload Files" /><br />
<img src="~/Content/Image/loading.gif" id="loadingImg" />
The fileInput is the file upload control, which uploads files on the server when the fileButton is clicked. Moreover the img tag will show the loading image when the file upload process is underway.
Add the following CSS code.
1
2
3
4
5
<style>
#loadingImg {
    display: none;
}
</style>

The jQuery AJAX to upload the Files

<script>
    $(document).ready(function () {
        $("#fileButton").click(function () {
            var files = $("#fileInput").get(0).files;
            var fileData = new FormData();
 
            for (var i = 0; i < files.length; i++) {
                fileData.append("fileInput", files[i]);
            }
 
            $.ajax({
                type: "POST",
                url: "/AjaxFileUpload/UploadFiles",
                dataType: "json",
                contentType: false, // Not to set any content header
                processData: false, // Not to process data
                data: fileData,
                success: function (result, status, xhr) {
                    alert(result);
                },
                error: function (xhr, status, error) {
                    alert(status);
                }
            });
        });
 
        $(document).ajaxStart(function () {
            $("#loadingImg").show();
            $("#fileButton").prop('disabled', true);
        });
 
        $(document).ajaxStop(function () {
            $("#loadingImg").hide();
            $("#fileButton").prop('disabled', false);
            $("#fileInput").val("");
        });
 
    });
</script>

==================================================================
Explanation : On the button click event I start by adding all the files in the FormData object, which are then posted to the controller’s action called UploadFiles. I do it using the jQuery AJAX method.

Controller Action that Saves the Files to the Server

Add the UploadFiles action to your controller. It gets called from the jQuery AJAX method.
Inside this action I loop through the files and save them to a folder.
1
2
3
4
5
6
7
8
9
10
11
12
[HttpPost]
public ActionResult UploadFiles()
{
    string path = Server.MapPath("~/Content/Upload/");
    HttpFileCollectionBase files = Request.Files;
    for (int i = 0; i < files.Count; i++)
    {
        HttpPostedFileBase file = files[i];
        file.SaveAs(path + file.FileName);
    }  
    return Json(files.Count + " Files Uploaded!");
}

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...