How do you accept a file upload in an ASP.NET Core controller action using IFormFile?
Short answer
An action parameter of type IFormFile automatically binds an uploaded file from a multipart/form-data request, giving access to its stream (OpenReadStream()), file name, content type, and length -- ASP.NET Core handles the multipart parsing automatically, letting you focus on…
Advertisement
AModel answer
An action parameter of type IFormFile automatically binds an uploaded file from a multipart/form-data request, giving access to its stream (OpenReadStream()), file name, content type, and length -- ASP.NET Core handles the multipart parsing automatically, letting you focus on what to do with the file's content.
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file) {
if (file.Length == 0) return BadRequest("Empty file");
using var stream = file.OpenReadStream();
await _storageService.SaveAsync(file.FileName, stream);
return Ok(new { file.FileName, file.Length });
}Real-world example
A document management API accepts PDF uploads via a simple IFormFile parameter, automatically getting the file's name, size, and content stream without manually parsing the multipart request body.
Likely follow-ups
- What's the maximum default upload size, and how do you configure it?
- How do you accept multiple files in a single request?
Related topics