Back to: ASP.NET Core Tutorials For Beginners and Professionals
Uploading Multiple Files using Buffering in ASP.NET Core MVC
In this article, I am going to discuss How to Upload Multiple Files using Buffering in ASP.NET Core MVC Application with Examples. Please read our previous article, where we discussed How to Upload a Single File in ASP.NET Core MVC Application. Let’s continue with the same application which we created in our previous article.
Modifying Index.cshtml:
Let’s update the Index.cshtml file under Views => Home folder to add form control for uploading multiple files. The form control encloses an input control of the type file and is followed by a button control of type submit, as shown in the below image.
Notice that
- form control has method = post, asp-controller=”Home” asp-action=”MultipleFileUpload” attributes.
- On submitting the form, the MultipleFileUpload action method of the Home controller will be executed.
- The name attribute of the file type input is MultipleFiles
- There is a multiple attribute on the input element of the type file. This element is required for supporting multiple file uploads.
So, open the Index.cshtml file and then copy and paste the following code into it.
@{ ViewData["Title"] = "Home Page"; } <form method="post" asp-controller="Home" asp-action="MultipleFileUpload" enctype="multipart/form-data"> <input type="file" multiple name="MultipleFiles" /> <button type="submit" name="Upload">Upload</button> </form>
Creating a Folder to Store the Uploaded Images:
Let’s create a new folder with the name Images within the project from Visual Studio. The uploaded files will be saved within this folder. To do so, right-click on the project and select Add, then select the New Folder option from the context menu, which will add a folder, and then rename the folder to Images. So, your project structure should look as shown below.
Modifying the Home Controller:
Let’s modify the Home Controller to add a new action method with the name MultipleFileUpload. In this action method, we will iterate over all the files which are uploaded and save them one after another. We will save the files to the Images folder we created in the previous step. Again, we will use the same CopyTo(Stream) method of the IFormFile interface to save the file, as shown in the image below. Please read our previous article, where we discussed the IFormFile interface in detail.
Notice that
We have an input parameter of type IEnumerable<IFormFile> for the action method. The name of the input parameter is MultipleFiles. The name of the input parameter must match the name of the file type input control that we have added.
The input parameter MultipleFiles contains the list of all the uploaded files. We are iterating over the files one by one, and for each file, we are creating a file stream that takes in the file path, file mode, and file access parameters.
Here, to give a unique name to each file, we are creating an object of GUID and appending this object with File_, and then using that string as the file name. Each time the for-loop executes, the GUID generates a unique value.
To get the content root path, we are using IWebHostEnvironment and getting the instance of it using dependency injection, as shown below.
To save the files in the Images folder, we are appending the folder name Images to the content root path, as shown below.
So, modify the Home Controller as follows:
using FileUploadInMVC.Models; using Microsoft.AspNetCore.Mvc; using System.Diagnostics; namespace FileUploadInMVC.Controllers { public class HomeController : Controller { private readonly IWebHostEnvironment _environment; public HomeController(IWebHostEnvironment environment) { _environment = environment; } public IActionResult Index() { return View(); } public IActionResult MultipleFileUpload(IEnumerable<IFormFile> MultipleFiles) { foreach (var file in MultipleFiles) { //Using Guid, we will give a unique name to each file string FileName = $"File_{Guid.NewGuid()}"; using var fileStream = new FileStream ( Path.Combine($"{_environment.ContentRootPath}//Images", $"{FileName}.png"), FileMode.Create, FileAccess.Write ); file.CopyTo(fileStream); } return RedirectToAction("Index"); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
Now run the application, and the index view of the home controller will be displayed, as shown below. The index view has a “Multiple File Upload” option using which we can upload multiple files.
Let’s upload multiple files using the “Multiple File Upload” form. Click on “Choose Files” and select multiple PNG or JPG files. After selecting the files, it will show the number of files chosen, as shown below. Click on the “Upload” button to process and save the uploaded files.
Please put a breakpoint at the entry point of the MultipleFileUpload action method. Once you click on the Upload button, the MultipleFileUpload action method of the HomeController will be hit. Right-click on the MultipleFiles parameter and then select the QuickWatch option from the context menu, as shown in the below image.
Notice it contains all the details about all the files we just uploaded, as shown below.
Click on F5 to continue with debugging. Once the file is copied to the specified path, the index page will be reloaded, and we should be able to see the uploaded file within the “Images” folder in the solution explorer, as shown below. After saving the file, we re-direct the application to the index page.
Let me know your thoughts on this in the comment section. In the next article. I am going to discuss How to Upload Files in ASP.NET Core MVC Applications using Streaming. In this article, I try to explain How to Upload Multiple Files in ASP.NET Core MVC Application with Examples. And I hope you enjoy this Upload Multiple Files in ASP.NET Core MVC Application article.