ASP.NET Core  

How to Upload Files in ASP.NET Core Web API?

Introduction

File upload functionality is a common requirement in modern web applications, including profile image uploads, document management systems, invoice processing, medical record systems, and cloud storage platforms. Implementing secure and efficient file upload in ASP.NET Core Web API requires understanding multipart/form-data handling, model binding, validation, storage strategies, and performance considerations.

This article provides a complete, real-world, and production-ready explanation of how to upload files in an ASP.NET Core Web API, including the internal mechanisms, security best practices, cloud storage options, advantages and disadvantages, and common mistakes developers make.

What Does File Upload Mean in ASP.NET Core?

File upload in ASP.NET Core Web API refers to receiving binary file data from a client (such as React, Angular, Postman, or mobile apps) using HTTP requests, usually with the multipart/form-data content type. The API processes the file and stores it locally, in a database, or in cloud storage.

In simple terms, the frontend sends a file, and the API receives and stores it safely.

How File Upload Works Internally

When a client uploads a file:

  1. The browser packages the file as multipart/form-data.

  2. The HTTP request is sent to the API endpoint.

  3. ASP.NET Core model binding processes the request.

  4. The file is exposed as IFormFile.

  5. The server saves it to a chosen storage location.

ASP.NET Core automatically parses multipart/form-data and provides access via IFormFile.

Real-World Analogy

Think of uploading a file like sending a parcel through courier.

  • The user packs the file (multipart form).

  • The courier (HTTP request) delivers it.

  • The warehouse (API server) receives it.

  • The warehouse stores it safely (file system, database, or cloud).

Security checks are like verifying the parcel contents before accepting it.

Step 1: Create File Upload Endpoint

Create a controller in ASP.NET Core Web API:

[ApiController]
[Route("api/[controller]")]
public class FileUploadController : ControllerBase
{
    [HttpPost("upload")]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return BadRequest("No file uploaded.");

        var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "Uploads");

        if (!Directory.Exists(uploadsFolder))
            Directory.CreateDirectory(uploadsFolder);

        var filePath = Path.Combine(uploadsFolder, file.FileName);

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

        return Ok(new { Message = "File uploaded successfully." });
    }
}

This endpoint accepts a single file and saves it locally.

Step 2: Configure Request Size Limits

By default, ASP.NET Core limits request body size. For large file uploads, configure limits in Program.cs:

builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 104857600; // 100 MB
});

For Kestrel configuration:

builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.Limits.MaxRequestBodySize = 104857600;
});

This ensures large files are accepted safely.

Step 3: Upload Multiple Files

To support multiple file uploads:

[HttpPost("upload-multiple")]
public async Task<IActionResult> UploadMultiple(List<IFormFile> files)
{
    foreach (var file in files)
    {
        var filePath = Path.Combine("Uploads", file.FileName);

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

    return Ok("Files uploaded successfully.");
}

Real Business Scenario: Document Management System

In a banking system:

  • Customers upload KYC documents.

  • Files are validated.

  • Stored in Azure Blob Storage.

  • Metadata saved in SQL Server.

  • Admin panel retrieves files securely.

In such systems, local storage is not recommended. Cloud storage is preferred.

File Storage Options

1. Local File System

  • Simple implementation

  • Suitable for small applications

  • Not scalable in distributed environments

2. Database Storage (VARBINARY)

  • Centralized storage

  • Slower for large files

  • Increases database size significantly

3. Cloud Storage (Recommended)

  • Azure Blob Storage

  • AWS S3

  • Scalable and secure

  • CDN integration possible

Example using Azure Blob Storage (conceptual example):

var blobClient = new BlobContainerClient(connectionString, "uploads");
await blobClient.CreateIfNotExistsAsync();

var blob = blobClient.GetBlobClient(file.FileName);
await blob.UploadAsync(file.OpenReadStream());

Security Best Practices

File upload endpoints are highly sensitive and must be secured.

  • Validate file type (MIME type and extension)

  • Restrict file size

  • Rename files using GUID to prevent overwriting

  • Scan files for malware

  • Store files outside wwwroot

  • Use authentication and authorization

Example: Safe File Name

var safeFileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";

Performance Considerations

  • Use streaming for large files

  • Avoid loading entire file into memory

  • Use async methods

  • Store files in cloud for scalability

  • Enable CDN for faster delivery

Advantages of File Upload in ASP.NET Core

  • Built-in multipart support

  • IFormFile abstraction

  • Easy integration with cloud storage

  • Async support for high performance

  • Secure model binding

Disadvantages

  • Large file memory usage if not handled properly

  • Security vulnerabilities if validation missing

  • Local storage not scalable

  • Requires proper server configuration

Common Mistakes Developers Make

  • Not validating file type

  • Storing files in wwwroot directly

  • Not limiting file size

  • Using original file name without sanitization

  • Blocking async calls

  • Ignoring antivirus scanning

When NOT to Store Files in Database

Avoid storing large files in SQL Server unless:

  • Files are very small

  • Strict transactional consistency required

  • Regulatory compliance demands it

Otherwise, prefer object storage.

Enterprise Architecture Flow

React Frontend → ASP.NET Core API → Validate File → Generate Unique Name → Upload to Azure Blob Storage → Save Metadata in SQL Server → Return File URL → CDN Distribution

This architecture ensures scalability and performance.

FAQ

Can we upload files larger than 1GB?

Yes, but streaming and proper server configuration are required.

Should we store images in database?

Only small images if necessary. Otherwise, store in blob storage and save URL in database.

How to secure file upload endpoint?

Use JWT authentication, validation, antivirus scanning, and strict size/type checks.

Conclusion

Uploading files in ASP.NET Core Web API requires careful handling of multipart/form-data requests, secure validation, and appropriate storage strategies. By using IFormFile, configuring request limits, validating file types and sizes, and leveraging scalable storage solutions such as Azure Blob Storage, developers can implement secure and high-performance file upload functionality suitable for enterprise-grade applications. Proper architectural planning, security enforcement, and performance optimization ensure that file upload features remain reliable, scalable, and production-ready in modern distributed systems.