In previous article, I mentioned Large file upload with Progress bar in ASP.NET Core (using Tus) but now in this article, I have mentioned how to upload file using AJAX in ASP.NET Core, without submitting form you can upload file using AJAX.
Step 1: Create a new project in your Visual Studio, I am using VS 2022, so open VS 2022, Click on "Create a project" -> then select "ASP.NET Core (Model View Controller)" as project template,
in the next Wizard step, name your web application as "FileUploadUsingAJAX" and then click "Next", then select .NET core version (I will be using .NET Core 6) and click on "Create", wait until Visual Studio Creates basic template files.
Step 2: Navigate to "HomeController.cs" in your project and add the file uploading code, as shown below
public async Task<IActionResult> AjaxUpload(IList<IFormFile> files)
{
var path = "";
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", formFile.FileName);
var filePath = Path.GetTempFileName();
using (var stream = System.IO.File.Create(path))
{
await formFile.CopyToAsync(stream);
}
}
}
return Json(true);
}
The above code is to get files as IList<IFormFile> which works for multiple file upload also.
Then we are looping each file and we are saving it as image in root path of ASP.NET Core app, which is "wwwroot"->"images"->yourfile in your project solution, you should create "images" folders in your solution first.
Files uploaded using the IFormFile
technique are buffered in memory or on disk on the server before processing. Inside the action method, the IFormFile
contents are accessible as a Stream.
So complete HomeController.cs code would look like this
using FileUploadUsingAJAX.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Net.Http.Headers;
namespace FileUploadUsingAJAX.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> AjaxUpload(IList<IFormFile> files)
{
var path = "";
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", formFile.FileName);
var filePath = Path.GetTempFileName();
using (var stream = System.IO.File.Create(path))
{
await formFile.CopyToAsync(stream);
}
}
}
return Json(true);
}
}
}
Step 3: Navigate to "Index.cshtml" which would be in Views -> Home -> Index.cshtml and use the below HTML/Javascript code to upload file on Button click using Javascript
@{
ViewData["Title"] = "Home Page";
}
<div class="upload-button">
<input id="fileUpload" name="fileUpload" type="file" /><br/>
<input type="button" onclick="uploadFiles('fileUpload');" value="Upload" class="btn btn-primary" />
</div>
@section Scripts{
<script>
function uploadFiles(inputId) {
var input = document.getElementById(inputId); //get file input id
var files = input.files; //get files
var formData = new FormData(); //create form
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]); //loop through all files and append
}
$.ajax(
{
url: "/Home/AjaxUpload",
data: formData, // send it as formData
processData: false,
contentType: false,
type: "POST", //type is post as we will need to post files
success: function (data) {
alert("Files Uploaded!");
}
}
);
}
</script>
}
HTML code, is very simple one, we have 1 input file type and 1 button, on clicking button named "Upload
", we are calling Javascript method uploadFiles("fileUpload")
In Javascript code, we are getting file input using document.getElementById
and creating formData
object, then appending files in formdata object.
Once we have file, we are using AJAX with URL, data as formData
and type as POST
.
That's it, if you will build and solution above, you will see output like below
As you can see in above GIF image, we were able to pass image file in Controller method and was able to save it inside solution folder "wwwroot" -> "images".
You may also like to read:
File upload in asp.net core mvc (single or multiple)
File upload on AWS S3 using C# in ASP.NET Core