You will take just 3 minutes to read and understand this jQuery file Upload tutorial that uses AJAX and does not perform page reloading when saving the files on the server.
Moreover it is able to upload multiple files at the same time.
<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.
<style>
#loadingImg {
display: none;
}
</style>
I will use the jQuery AJAX Method to upload the files. So add the below jQuery code to your View.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<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.
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.
[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!");
}
Check the below link: