File uploads and downloads are common requirements in modern web applications. Whether an application handles employee documents, product images, customer reports, videos, or backup files, developers often need to process files of different sizes.
For small files, reading the entire file into memory may not create noticeable problems. However, when an application starts handling large files or multiple uploads simultaneously, memory consumption can increase quickly.
Consider an ASP.NET Core API that allows users to upload documents up to several hundred megabytes. If every uploaded file is loaded completely into application memory before processing, multiple concurrent requests can consume a significant amount of available memory.
This can lead to increased garbage collection activity, slower response times, application instability, and eventually out-of-memory errors.
ASP.NET Core provides several ways to process large files without loading their complete contents into application memory. Developers can use streaming, multipart request processing, file streams, and direct cloud storage uploads to build more memory-efficient applications.
In this article, we will explore why large files create memory problems, how to implement streaming in ASP.NET Core, and which approaches are suitable for production applications.
Why Large Files Increase Application Memory Consumption
One common mistake in file processing is reading the complete file into a byte array before saving or processing it.
Consider the following example:
[HttpPost("upload")]
public async Task<IActionResult> Upload(
IFormFile file)
{
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
byte[] fileData = memoryStream.ToArray();
return Ok(new
{
FileName = file.FileName,
Size = fileData.Length
});
}
This implementation reads the uploaded file into a MemoryStream and then creates another byte array containing its contents.
The problem becomes more serious when multiple requests execute simultaneously.
For example, if several users upload large files at the same time, the application may allocate substantial memory for those requests.
The actual memory requirement can be higher than the file size because additional buffers, temporary allocations, and processing operations may also consume memory.
Understanding the Impact of Concurrent Uploads
Consider an application that receives multiple file uploads.
Upload Size | Concurrent Uploads | Approximate File Data |
|---|
20 MB | 5 | 100 MB |
50 MB | 10 | 500 MB |
100 MB | 10 | 1 GB |
250 MB | 8 | 2 GB |
These figures represent only the combined file contents. They do not include application memory, framework buffers, temporary allocations, or other processing requirements.
This is why a file upload implementation that works perfectly during development may fail when deployed to production.
The solution is to avoid unnecessary full-file memory allocations.
Understanding Streaming in ASP.NET Core
Streaming allows an application to process data in smaller portions instead of loading the entire file into memory.
Rather than reading a complete file into a byte array, the application reads a portion of the file, processes it, and continues until the entire file has been handled.
ASP.NET Core supports streaming through standard .NET stream APIs.
For example, an application can copy an incoming file stream directly to a destination file:
[HttpPost("upload")]
public async Task<IActionResult> Upload(
IFormFile file,
CancellationToken cancellationToken)
{
if (file == null || file.Length == 0)
{
return BadRequest("Please select a file.");
}
var uploadDirectory = Path.Combine(
Directory.GetCurrentDirectory(),
"Uploads");
Directory.CreateDirectory(uploadDirectory);
var filePath = Path.Combine(
uploadDirectory,
Guid.NewGuid().ToString("N"));
await using var fileStream = new FileStream(
filePath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None,
81920,
FileOptions.Asynchronous);
await file.CopyToAsync(
fileStream,
cancellationToken);
return Ok(new
{
Message = "File uploaded successfully."
});
}
This approach avoids creating an additional byte array containing the complete file.
The application copies the incoming stream to the destination using buffered I/O.
However, there is an important distinction: using IFormFile does not automatically mean the entire upload is streamed directly to the destination. ASP.NET Core's multipart form processing may buffer uploaded files in memory and temporary storage before the controller receives the IFormFile.
For large uploads where controlling buffering is important, direct request-body streaming is a better option.
Implementing Direct File Streaming in ASP.NET Core
When applications need more control over large uploads, they can process the incoming request body directly.
Instead of relying on automatic multipart form model binding, the application reads the request body as a stream.
Step 1: Create a Streaming Upload Endpoint
The following example demonstrates direct streaming of a request body into a file.
[HttpPost("stream-upload")]
[DisableRequestSizeLimit]
public async Task<IActionResult> StreamUpload(
CancellationToken cancellationToken)
{
var uploadDirectory = Path.Combine(
Directory.GetCurrentDirectory(),
"Uploads");
Directory.CreateDirectory(uploadDirectory);
var filePath = Path.Combine(
uploadDirectory,
Guid.NewGuid().ToString("N"));
await using var fileStream = new FileStream(
filePath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None,
81920,
FileOptions.Asynchronous);
await Request.Body.CopyToAsync(
fileStream,
cancellationToken);
return Ok(new
{
Message = "Upload completed.",
Size = fileStream.Length
});
}
This endpoint reads the incoming HTTP request body and copies it directly to a file.
The application does not need to create a MemoryStream containing the entire request body.
The buffer size controls the amount of data used by the file stream during its operations.
The DisableRequestSizeLimit attribute removes the ASP.NET Core request-size limit for this endpoint. It should not be used without implementing an appropriate upload limit elsewhere.
For production applications, configure a maximum upload size at the application or hosting layer and reject requests that exceed it.
Step 2: Configure an Upload Size Limit
Removing the default request-size limit does not mean unlimited uploads should be accepted.
An application should define an acceptable file size based on its business requirements.
For example:
private const long MaxUploadSize =
500 * 1024 * 1024;
[HttpPost("upload")]
[RequestSizeLimit(MaxUploadSize)]
public async Task<IActionResult> Upload(
CancellationToken cancellationToken)
{
if (Request.ContentLength > MaxUploadSize)
{
return StatusCode(
StatusCodes.Status413PayloadTooLarge);
}
// Process the incoming stream.
return Ok();
}
The ContentLength check provides an additional application-level validation when the request declares its length.
However, Content-Length is not guaranteed to be present in every request. For reliable enforcement, the application must also count the bytes actually read from the stream.
For example, a bounded copying operation can stop processing as soon as the configured limit is exceeded.
Handling Multipart File Uploads Without Loading Entire Files
Many applications use multipart/form-data because it allows users to upload files along with additional form fields.
ASP.NET Core provides MultipartReader for manually processing multipart request bodies.
This is useful when an application needs to process individual sections without relying on automatic IFormFile model binding.
A simplified example looks like this:
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
[HttpPost("multipart-upload")]
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadMultipart(
CancellationToken cancellationToken)
{
if (!MediaTypeHeaderValue.TryParse(
Request.ContentType,
out var mediaType))
{
return BadRequest("Invalid content type.");
}
var boundary = HeaderUtilities.RemoveQuotes(
mediaType.Boundary).Value;
if (string.IsNullOrWhiteSpace(boundary))
{
return BadRequest("Missing multipart boundary.");
}
var reader = new MultipartReader(
boundary,
Request.Body);
var section = await reader.ReadNextSectionAsync(
cancellationToken);
while (section != null)
{
if (ContentDispositionHeaderValue.TryParse(
section.ContentDisposition,
out var disposition))
{
if (disposition.IsFileDisposition())
{
var filePath = Path.Combine(
"Uploads",
Guid.NewGuid().ToString("N"));
Directory.CreateDirectory("Uploads");
await using var fileStream = new FileStream(
filePath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None,
81920,
FileOptions.Asynchronous);
await section.Body.CopyToAsync(
fileStream,
cancellationToken);
}
}
section = await reader.ReadNextSectionAsync(
cancellationToken);
}
return Ok("Upload completed.");
}
The DisableFormValueModelBinding attribute in this example represents a custom resource filter that prevents automatic form model binding. It must be implemented and registered separately.
This is important because automatic form processing can consume and buffer the request before the application starts reading it directly.
A production implementation should also validate multipart sections, enforce limits on the number of sections, and handle unexpected content types.
Streaming Large File Downloads
Memory optimization is equally important when returning large files from an ASP.NET Core API.
Consider an endpoint that reads a complete file into memory:
[HttpGet("download")]
public async Task<IActionResult> Download()
{
var filePath = "Uploads/report.pdf";
byte[] fileData = await System.IO.File.ReadAllBytesAsync(
filePath);
return File(
fileData,
"application/pdf",
"report.pdf");
}
This implementation loads the entire file into a byte array before returning the response.
For large files, returning a file stream is generally more memory-efficient.
[HttpGet("download")]
public IActionResult Download()
{
var filePath = "Uploads/report.pdf";
var stream = new FileStream(
filePath,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
81920,
FileOptions.Asynchronous);
return File(
stream,
"application/pdf",
"report.pdf");
}
ASP.NET Core can write the file content to the HTTP response without requiring the application to create a complete byte array first.
The framework manages the response stream lifecycle for this file result.
For production applications, validate that the requested file exists and ensure users are authorized to access it before returning the stream.
Choosing the Right File Processing Approach
Different applications require different file handling strategies.
Approach | Memory Usage | Suitable Scenario |
|---|
ReadAllBytesAsync | High for large files | Small files |
MemoryStream | Can grow with file size | Small in-memory processing |
IFormFile | May use memory and temporary disk buffering | Standard multipart uploads |
Direct request streaming | Uses bounded buffers when implemented correctly | Large uploads |
FileStream | Uses buffered file operations | File storage and downloads |
Cloud storage streaming | Avoids storing complete files in application memory | Large-scale file storage |
The important decision is not simply whether to use streams. Developers should also consider where buffering happens, how files are stored, and how concurrent requests affect the application.
Advantages and Disadvantages of Streaming
Advantages
Lower memory consumption: The application avoids unnecessary full-file byte array allocations.
Better concurrency: Multiple uploads can be processed using bounded buffers rather than complete file copies in memory.
Improved scalability: Streaming helps applications handle larger files without requiring memory proportional to the total file size.
Flexible processing: Files can be copied, inspected, transformed, or transferred incrementally.
Better cloud integration: Streams can be used with object storage services without first loading complete files into application memory.
Disadvantages
More implementation complexity: Direct streaming requires careful request parsing and validation.
Error handling: Interrupted uploads and partial files need proper cleanup.
Resource management: Streams must be disposed correctly.
Processing limitations: Some operations require seeking or access to the complete file, which may need temporary storage.
Storage dependency: Streaming to disk still requires sufficient storage capacity and appropriate file permissions.
Best Practices for Production Applications
When implementing large file processing, consider the following practices.
Avoid unnecessary byte arrays. Do not use ReadAllBytesAsync or MemoryStream for large files unless the application genuinely needs the complete content in memory.
Configure upload limits. Define maximum file sizes at the application, hosting, and infrastructure levels.
Use cancellation tokens. Pass request cancellation tokens to asynchronous stream operations so abandoned requests do not continue consuming resources unnecessarily.
Validate file content. Do not trust file extensions or client-provided content types. Validate actual file content according to the application's requirements.
Use generated file names. Avoid using user-provided file names directly as storage paths. Generate unique names and keep the original name as metadata when needed.
Store files outside the application directory. Use dedicated storage locations with restricted permissions rather than exposing uploaded files through the public web root.
Monitor temporary storage. Multipart processing and upload workflows can consume temporary disk space. Monitor available storage and clean up abandoned temporary files.
Protect against concurrent uploads. Configure appropriate connection limits, request limits, and application-level concurrency controls.
Use cloud object storage for large workloads. When an application handles many large files, consider uploading directly to services such as Azure Blob Storage or Amazon S3 using secure, time-limited upload permissions.
Test under realistic conditions. Test large uploads, interrupted connections, simultaneous requests, and storage failures before deploying the implementation.
Common Mistakes and Troubleshooting
Problem | Possible Cause | Recommended Solution |
|---|
High memory consumption | Complete files loaded into byte arrays | Use streaming |
HTTP 413 error | Request size limit exceeded | Review application and hosting limits |
Upload stops unexpectedly | Client disconnect or request cancellation | Handle cancellation and clean up partial files |
Temporary disk fills up | Buffered uploads are not cleaned up | Monitor temporary storage and configure cleanup |
Access denied when saving files | Incorrect directory permissions | Configure storage permissions |
Corrupted uploaded files | Incomplete stream copying or interrupted uploads | Validate file size and completion |
Application becomes slow during uploads | Excessive concurrent file processing | Introduce concurrency limits |
One important production consideration is that streaming does not automatically solve every resource problem. Disk storage, network bandwidth, open file handles, and CPU-intensive file processing can still become bottlenecks.
For example, an application that streams hundreds of large files simultaneously may use relatively little managed memory but still experience storage or network saturation.
Therefore, monitor memory usage alongside disk activity, network throughput, request duration, and failed uploads.
Summary
Handling large files efficiently is an important part of building scalable ASP.NET Core applications. Reading complete files into memory may work for small uploads, but it can create serious resource problems when file sizes and concurrent requests increase.
ASP.NET Core provides several options for efficient file processing, including FileStream, request-body streaming, MultipartReader, and streamed file downloads.
The most important consideration is understanding where buffering occurs. Using IFormFile is convenient for standard uploads, but it does not guarantee that the incoming file is never buffered.
For applications that handle large files, direct streaming with appropriate request limits and validation provides greater control over memory consumption.
By combining streaming, secure storage, cancellation handling, resource monitoring, and appropriate concurrency limits, developers can build ASP.NET Core applications that handle large files more reliably without unnecessary memory allocations.
Join the conversation! Your thoughts help the community grow.