In an ASP.NET Core 10 controller, how do you accept an uploaded file with IFormFile and save it to disk?
answer
- multipart/form-data form
- parameter name matches the field name
- Length, FileName, ContentType, OpenReadStream
- CopyToAsync into a FileStream
- IFormFileCollection or List<IFormFile>
basics
~10 sPost a multipart/form-data form and declare an IFormFile parameter named like the file field. Check Length, then CopyToAsync into a FileStream under a server-generated name; the file was already buffered before the action ran.
solid answer
~40 sThe client sends `multipart/form-data`, for example `<form method="post" enctype="multipart/form-data">` with `<input type="file" name="scan">`. The action declares `IFormFile scan`; the parameter name must match the field name, or you set it with `[FromForm(Name = "scan")]`. The parameter is `null` when the field is missing, and `Length` is 0 for an empty file. To save it, open a `FileStream` on a path you generate and `await scan.CopyToAsync(stream, ct)`; `OpenReadStream()` gives a read stream if you process it instead. For several files use `IFormFileCollection`, `List<IFormFile>` or `IEnumerable<IFormFile>`. By the time the action runs, model binding has already read the whole form: each file is held in memory up to 64 KB and spilled to a temporary file beyond that, so `IFormFile` is the buffered approach, fine for modest sizes.
code
csharp · 21 lines[ApiController]
[Route("api/records")]
public class RecordsController(IOptions<UploadOptions> options) : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Upload(IFormFileCollection scans, CancellationToken ct)
{
var saved = 0;
foreach (var scan in scans)
{
if (scan.Length == 0) continue;
var path = Path.Combine(options.Value.UploadRoot, Path.GetRandomFileName());
await using var target = new FileStream(path, FileMode.CreateNew);
await scan.CopyToAsync(target, ct);
saved++;
}
return Ok(new { saved });
}
}
public class UploadOptions { public string UploadRoot { get; set; } = ""; }go deeper
Recall the multipart form, an IFormFile parameter named after the field, the Length check and CopyToAsync to a generated path.
Explain that the form is buffered before the action runs, the 64 KB memory threshold, the temp folder and which IFormFile members are client claims.
Know when buffering stops being acceptable and plan limits, storage location and validation for uploads before they reach production.
Decide where uploaded content lives (local disk, object storage, database) and what the upload path must guarantee for regulated documents.
## The request side A browser sends files only in a **multipart/form-data** body. In the telehealth app, a clinic uploads a scanned referral letter: ```razor <form method="post" action="/api/records" enctype="multipart/form-data"> <input type="file" name="scan" /> <input type="text" name="patientId" /> <button type="submit">Upload</button> </form> ``` Without the `enctype`, the browser sends only the file name as text and the file never arrives. ## The action side ```csharp [HttpPost("api/records")] public async Task<IActionResult> Upload(IFormFile scan, [FromForm] Guid patientId, CancellationToken ct) { if (scan is null || scan.Length == 0) return BadRequest("No file."); var path = Path.Combine(_options.Value.UploadRoot, Path.GetRandomFileName()); await using var stream = new FileStream(path, FileMode.CreateNew); await scan.CopyToAsync(stream, ct); return Created(); } ``` Key points: - **Name matching.** Binding looks for a form file whose field name equals the parameter name (`scan`). A mismatch leaves the parameter `null`; nothing throws, although a required parameter (a non-nullable `IFormFile` in a nullable-enabled project counts as required) also records a ModelState error, which `[ApiController]` turns into a 400. - **Several files.** `IFormFileCollection`, `List<IFormFile>` or `IEnumerable<IFormFile>` bind every file sent under that name; `IFormFileCollection.GetFiles("scan")` filters by name when you read `Request.Form.Files` directly. - **Inside a model.** An `IFormFile` property on a form-bound DTO binds the same way, together with ordinary form fields such as `patientId`. - **Saving.** `CopyToAsync(Stream, CancellationToken)` writes the content; `OpenReadStream()` returns a read-only stream when you want to hash, scan or forward the bytes instead. ## What IFormFile tells you | Member | Meaning | Trust it? | |---|---|---| | `Length` | bytes actually received for the file | yes, measured by the server | | `Name` | form field name (`scan`) | it is just the field name | | `FileName` | name the client claims | no; never use it as a storage path | | `ContentType` | MIME type the client claims | no; verify the content | | `ContentDisposition` | raw header of the part | no | ## Buffered, not streamed `IFormFile` is the **buffered** model. Before the action runs, MVC reads the entire form: 1. Each file part is copied into a buffer: memory up to `FormOptions.MemoryBufferThreshold` (64 KB), then a temporary file on disk. 2. Temporary files go to the folder named by the `ASPNETCORE_TEMP` environment variable, or the user's temp folder, and are deleted when the request ends. 3. Only then is your action called with `IFormFile` objects pointing at those buffers. That is why `IFormFile` is fine for documents of a few megabytes, and why very large uploads move to streaming with `MultipartReader`, where nothing is buffered before your code runs. ## Reading the form yourself An action can skip the parameter and read `Request.Form.Files`, an `IFormFileCollection`, or call `await Request.ReadFormAsync(ct)`. That is the same buffered parse, moved from model binding into your code: - `Request.Form.Files.GetFile("scan")` returns the first file sent under that field name, or `null`. - `Request.Form.Files.GetFiles("scan")` returns every file sent under that name. - When **model binding** matches files, the comparison of field name and parameter name is case-insensitive, and a file input the user left empty (zero length and no file name) is skipped rather than bound as an empty `IFormFile`. Reading the form manually is useful when the field name is only known at run time; otherwise the parameter is clearer and shows up in the endpoint's metadata. ## Common mistakes - Writing to `Path.Combine(root, scan.FileName)`: the client controls that string. - Saving under `wwwroot`, where the static files middleware would serve uploads publicly. - Calling `CopyTo` (synchronous) in a busy app instead of `CopyToAsync`. - Forgetting the size limits: by default Kestrel stops a request body at 30,000,000 bytes, before any of this code runs. ## Minimal APIs A Minimal API handler can take `IFormFile` or `IFormFileCollection` parameters too; how those parameters are inferred and the antiforgery check that form binding triggers there are covered with Minimal API handlers and antiforgery.
- Why is the IFormFile parameter null even though the browser clearly sent a file?Usually a name mismatch: binding matches the form field name, so `<input name="file">` does not bind to a parameter called `scan`. Rename one side or use `[FromForm(Name = "file")]`. The other common cause is a form without `enctype="multipart/form-data"`, which sends no file part at all.
- Where does a 5 MB IFormFile live while the action runs?In a temporary file. Form parsing buffers each file part in memory only up to `FormOptions.MemoryBufferThreshold` (64 KB) and then switches to a file in the `ASPNETCORE_TEMP` folder or the user's temp folder. That file is deleted at the end of the request, so copy it somewhere permanent inside the action.
- IFormFile streams the upload to the action while the client is still sending it.
- Saving to Path.Combine(uploadRoot, file.FileName) is safe because browsers send only the name.
- IFormFile.ContentType proves what kind of file was uploaded.
- A missing file field makes model binding throw an exception.
- Every uploaded file is held entirely in memory until the request ends.