File uploads are common in modern web applications. Users upload documents, images, videos, reports, backups, and other files through ASP.NET Core APIs. Uploading a small file is usually straightforward, but handling large files introduces additional challenges.
A common implementation accepts an uploaded file through IFormFile, copies it into a MemoryStream, and then saves it to storage. This approach works for small files, but it can create unnecessary memory pressure when multiple users upload large files simultaneously.
For example, if several users upload files of hundreds of megabytes and the application copies each file into memory, the application can consume a significant amount of memory. This can lead to garbage collection pressure, slow requests, and even application failures.
ASP.NET Core supports streaming techniques that allow an application to process incoming file data without loading the complete file into memory. In this article, we will explore how to implement large file uploads, configure request limits, handle cancellation, and build a reliable upload endpoint.
Understanding Buffered and Streaming File Uploads
ASP.NET Core supports two general approaches for receiving uploaded files: buffering and streaming.
Buffered File Uploads
The most common approach uses IFormFile. ASP.NET Core's model binding reads multipart form data and makes uploaded files available through the IFormFile interface.
A simple controller action looks like this:
[HttpPost("upload")]
public async Task<IActionResult> Upload(
IFormFile file,
CancellationToken cancellationToken)
{
if (file == null || file.Length == 0)
{
return BadRequest("No file was uploaded.");
}
var path = Path.Combine(
"uploads",
Path.GetFileName(file.FileName));
await using var stream = new FileStream(path, FileMode.Create);
await file.CopyToAsync(stream, cancellationToken);
return Ok("File uploaded successfully.");
}This implementation is convenient, but IFormFile uses buffered model binding. Uploaded content is buffered in memory or temporary storage before the application processes it. Files larger than the configured memory threshold are generally moved to temporary disk storage.
Therefore, using IFormFile does not necessarily mean that the entire file stays in application memory. However, buffering can still create significant memory and disk pressure when many large uploads happen concurrently.
Streaming File Uploads
Streaming processes the incoming request body incrementally. Instead of waiting for the complete file to become available through model binding, the application reads smaller chunks and writes them directly to the destination.
For example, an application can read 64 KB at a time and immediately write each chunk to a file.
This approach avoids holding the complete file in a MemoryStream. It is especially useful for applications that accept large files or handle many concurrent uploads.
Streaming primarily reduces memory and temporary-storage requirements. It does not automatically make the upload faster because network bandwidth, disk performance, and other infrastructure limitations still apply.
Implement a Streaming File Upload Endpoint
For a single-file upload API, one straightforward option is to send the file as the raw HTTP request body using application/octet-stream.
This avoids multipart form parsing and allows the application to read the request body directly.
Configure the Upload Directory
Uploaded files should be stored outside the application directory and outside publicly accessible web folders.
Create an upload directory and configure its location through application settings.
For example, add the following configuration:
{
"FileStorage": {
"UploadPath": "D:\\AppData\\Uploads",
"MaxFileSizeBytes": 524288000
}
}This example allows files up to 500 MB. The actual limit should depend on application requirements and available infrastructure.
Create a configuration class:
public sealed class FileStorageOptions
{
public string UploadPath { get; set; } = string.Empty;
public long MaxFileSizeBytes { get; set; }
}Register the configuration in Program.cs:
builder.Services.Configure<FileStorageOptions>(
builder.Configuration.GetSection("FileStorage"));In production, use an appropriate storage location for the hosting environment. For containerized applications, consider a persistent volume or cloud object storage rather than relying on the container's temporary filesystem.
Create the Streaming Endpoint
The following Minimal API endpoint reads the request body in chunks and writes the content directly to disk.
app.MapPost("/upload", async (
HttpContext context,
IOptions<FileStorageOptions> storageOptions) =>
{
var options = storageOptions.Value;
var request = context.Request;
if (string.IsNullOrWhiteSpace(options.UploadPath))
{
return Results.Problem(
"Upload storage is not configured.");
}
var maxFileSize = options.MaxFileSizeBytes;
if (maxFileSize <= 0)
{
return Results.Problem(
"Invalid upload size configuration.");
}
if (request.ContentLength > maxFileSize)
{
return Results.BadRequest("File is too large.");
}
Directory.CreateDirectory(options.UploadPath);
var fileName = $"{Guid.NewGuid():N}.upload";
var filePath = Path.Combine(
options.UploadPath,
fileName);
var buffer = new byte[64 * 1024];
long totalBytes = 0;
try
{
await using var output = new FileStream(
filePath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None,
buffer.Length,
FileOptions.Asynchronous);
while (true)
{
var bytesRead = await request.Body.ReadAsync(
buffer,
context.RequestAborted);
if (bytesRead == 0)
{
break;
}
totalBytes += bytesRead;
if (totalBytes > maxFileSize)
{
throw new InvalidOperationException(
"File size limit exceeded.");
}
await output.WriteAsync(
buffer.AsMemory(0, bytesRead),
context.RequestAborted);
}
return Results.Ok(new
{
FileName = fileName,
Size = totalBytes,
Message = "File uploaded successfully."
});
}
catch (OperationCanceledException)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
throw;
}
catch (InvalidOperationException)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
return Results.BadRequest("File size limit exceeded.");
}
catch
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
throw;
}
});The example uses a generated file name rather than trusting a name supplied by the client. It also checks the total number of bytes received, not just Content-Length. This is important because some requests do not provide a Content-Length header.
The application reads the request body into a reusable 64 KB buffer. Each chunk is written to the destination before the next chunk is read. Consequently, the application does not need a MemoryStream containing the complete uploaded file.
The RequestAborted cancellation token is passed to both read and write operations. If the client disconnects or cancels the request, the operation can stop and the incomplete file can be removed.
This example uses a raw request body, so the client must send the file as application/octet-stream rather than multipart/form-data. The generated .upload file is also only a temporary storage representation; production applications should preserve validated file metadata and move completed uploads into an appropriate storage lifecycle.
Join the conversation! Your thoughts help the community grow.