Uploading Multiple Files in C#: A Practical Guide

Estimated read time 2 min read

Uploading Multiple Files in C#: A Practical Guide

Uploading multiple files is a common requirement in many web applications, and C# provides a straightforward way to handle this task. In this article, we’ll explore how to implement a file upload functionality for multiple files using ASP.NET Core, showcasing a practical example.

1. Create an ASP.NET Core Web Application:

Start by creating a new ASP.NET Core web application. You can do this using the following command in your terminal:

dotnet new web -n MultipleFileUpload
cd MultipleFileUpload

2. Modify the Controller:

Next, let’s modify the controller to handle file uploads. In this example, we’ll create a simple controller with an action to handle the file uploads.

// File: FileUploadController.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

[Route("api/[controller]")]
[ApiController]
public class FileUploadController : ControllerBase
{
    private readonly IWebHostEnvironment _environment;

    public FileUploadController(IWebHostEnvironment environment)
    {
        _environment = environment;
    }

    [HttpPost]
    public async Task<IActionResult> UploadFiles(List<IFormFile> files)
    {
        long size = files.Sum(f => f.Length);

        foreach (var formFile in files)
        {
            if (formFile.Length > 0)
            {
                var filePath = Path.Combine(_environment.ContentRootPath, "uploads", formFile.FileName);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await formFile.CopyToAsync(stream);
                }
            }
        }

        return Ok(new { count = files.Count, size });
    }
}

3. Configure File Upload in Startup:

Ensure file uploads are configured in your Startup.cs file. Add the following lines in the ConfigureServices method:

services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = int.MaxValue;
});

services.Configure<FormOptions>(options =>
{
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartBodyLengthLimit = int.MaxValue;
    options.MemoryBufferThreshold = int.MaxValue;
});

4. Create the Upload Folder:

Create a folder named “uploads” in your project’s root directory to store the uploaded files.

5. Test the File Upload:

Now, run your application (dotnet run), and you can test the file upload functionality by sending a POST request to the /api/FileUpload endpoint with multiple files.

Conclusion:

Implementing multiple file uploads in C# with ASP.NET Core is a straightforward process. By leveraging the capabilities of the IFormFile interface and handling the uploaded files in the controller, you can easily integrate this functionality into your web applications. This example provides a solid foundation for expanding file upload capabilities based on your specific project requirements.

Related Articles