How to Upload Multiple Files in ASP.NET Core MVC

How to Upload Multiple Files in ASP.NET Core MVC:

In this article, I will discuss How to Upload Multiple Files in ASP.NET Core MVC Application with Examples. Please read our previous article discussing How to Delete Images in ASP.NET Core MVC Application with Examples. Let’s continue with the application we worked on in previous articles.

How do you upload multiple files in ASP.NET Core MVC?

Uploading multiple files in ASP.NET Core MVC can be achieved with a combination of the HTML form, the controller, and model binding. Here’s a step-by-step guide to accomplish this:

Create a Model to Represent the File Input

First, you need a model that represents the file input. This model typically contains a property of type List<IFormFile>. So, create a class file named FileUploadModel.cs and then copy and paste the following code.

namespace FileUploadInMVC.Models
{
    public class FileUploadModel
    {
        public IEnumerable<IFormFile> MultipleFiles { get; set; }
    }
}
Create an Action Method:

Please add the following action MultipleFileUpload method within the FileUpload Controller. This action method renders a view representing the form, allowing the user to upload multiple files.

public IActionResult MultipleFileUpload()
{
    return View();
}
Create an HTML Form in the View

Create a form with enctype=”multipart/form-data” in your Razor view to enable file uploads. Use an input element of the type file and set its multiple attributes to allow multiple file selections. So, create a view named MultipleFileUpload.cshtml within the Views/FileUpload folder and then copy and paste the following code.

@{
    ViewData["Title"] = "MultipleFileUpload";
}

<h1>Multiple File Upload</h1>
<hr />
<div class="row">
    <div class="col-md-12">
        <form method="post" asp-controller="FileUpload" asp-action="MultipleFileUpload"
              enctype="multipart/form-data">
            <div asp-validation-summary="All" class="text-danger"></div>
            <input type="file" name="MultipleFiles" multiple accept=".jpg,.png,.gif" class="form-control" />
            <button type="submit" name="Upload" class="btn btn-primary">Upload</button>
        </form>
    </div>
</div>
Notice that
  • form control has method = post, asp-controller=”FileUpload” asp-action=”MultipleFileUpload” attributes.
  • The form element has the attribute enctype=”multipart/form-data” which enables file uploading.
  • Upon submission of the form, the MultipleFileUpload action method of the FileUpload 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.
Handle the File Upload in the Controller

In your controller, create an action method to handle the file upload. The method should match the name specified in the asp-action of the form. So, add the following MultipleFileUpload action method within the FileUpload Controller. We save the uploaded files to the database and the File System in the code below.

[HttpPost]
public async Task<IActionResult> MultipleFileUpload(FileUploadModel model)
{
    foreach (var file in model.MultipleFiles)
    {
        if (file.Length > 0)
        {
            // Process each file here

            //Creating a unique File Name
            var uniqueFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);

            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", uniqueFileName);

            //Using Buffering
            //using (var stream = System.IO.File.Create(filePath))
            //{
            //    // The file is saved in a buffer before being processed
            //    await file.CopyToAsync(stream);
            //}

            //Using Streaming
            using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                //This will save to Local folder
                await file.CopyToAsync(stream);
            }

            // Create an instance of FileModel
            var fileModel = new FileModel
            {
                FileName = uniqueFileName,
                Length = file.Length,
                ContentType = file.ContentType,
                Data = ConvertToByteArray(filePath)
            };

            // Save to database
            EFCoreDbContext _context = new EFCoreDbContext();
            _context.Files.Add(fileModel);
            await _context.SaveChangesAsync();

            return View("UploadSuccess");
        }
    }

    return View();
}
Running the Application:

Before testing this functionality, remove all the records from the database and all the images from the wwwroot/uploads folder.

Now run the application and navigate to the FileUpload/MultipleFileUpload URL, which will display the following page. The MultipleFileUpload view has a “Multiple File Upload” option, which we can use to upload multiple files.

How to Upload Multiple Files in ASP.NET Core MVC Application with Examples

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.

How to Upload Multiple Files in ASP.NET Core MVC

Once you click on the Upload button, it will upload the images, which you can see inside the Uploads folder, as shown in the image below.

How do you upload multiple files in ASP.NET Core MVC?

If you verify the database, you will see the data as expected, as shown in the image below.

When should you use multiple file uploading in ASP.NET Core MVC?

Tips and Considerations

  • Validation: Always validate the file type and size before processing to prevent malicious uploads.
  • Asynchronous Processing: Use async methods to handle file uploads, especially if the files are large or if you expect high traffic.
  • Error Handling: Implement error handling to manage exceptions that may occur during file uploads.
When should you use multiple file uploading in ASP.NET Core MVC?

Using multiple file uploading in ASP.NET Core MVC is particularly beneficial in scenarios where users need to upload more than one file at a time, often for convenience, efficiency, or functionality requirements. Here are some key scenarios where implementing multiple file uploading is advantageous:

  • Bulk Data Uploads: In applications that require bulk data processing, such as importing many records from files (e.g., CSV, Excel), allowing users to upload multiple files at once can save time and improve efficiency.
  • Photo Galleries or Media Libraries: When building applications like photo galleries, media libraries, or content management systems, users often need to upload several images or media files simultaneously. Multiple file uploading streamlines this process.
  • Document Management Systems: For platforms that handle various types of documents (e.g., PDFs, Word documents), such as legal, academic, or corporate document management systems, users frequently need to upload multiple related documents in a single session.
  • E-commerce Product Management: In e-commerce platforms, vendors or administrators may need to upload multiple images or documents for product listings. Enabling multiple file uploads simplifies this task.
  • User Profile Creation or Updates: Applications that allow users to create detailed profiles with various documents (like identity proofs, certifications, or portfolios) benefit from multiple file uploads.
  • Educational and Training Platforms: For online education or training portals, instructors might need to upload multiple educational resources, assignments, or course materials simultaneously.
  • Backup and Restore Applications: In systems where users can back up and restore data, allowing the uploading of multiple backup files at once can be very useful.

In the next article, I will discuss How to Export Data to an Excel File in an ASP.NET Core MVC Application with Examples. In this article, I try to explain How to Upload Multiple Files in an ASP.NET Core MVC Application with Examples. And I hope you enjoy this How to Upload Multiple Files in ASP.NET Core MVC article.

Leave a Reply

Your email address will not be published. Required fields are marked *