How do you accept and process multiple files uploaded in a single request?
Short answer
An action parameter of type IFormFileCollection or List automatically binds all files present in a multipart request with matching form field names, letting you iterate and process each uploaded file, useful for batch upload scenarios like a photo gallery accepting several…
Advertisement
AModel answer
An action parameter of type IFormFileCollection or List<IFormFile> automatically binds all files present in a multipart request with matching form field names, letting you iterate and process each uploaded file, useful for batch upload scenarios like a photo gallery accepting several images at once.
[HttpPost("upload-multiple")]
public async Task<IActionResult> UploadMultiple(List<IFormFile> files) {
var results = new List<string>();
foreach (var file in files) {
if (file.Length > 0) {
await _storageService.SaveAsync(file.FileName, file.OpenReadStream());
results.Add(file.FileName);
}
}
return Ok(new { uploadedFiles = results });
}Real-world example
A photo gallery feature lets users select and upload up to 10 images in a single form submission, bound automatically as a List<IFormFile> and processed in a single loop rather than requiring 10 separate upload requests.
Likely follow-ups
- How would you enforce a maximum number of files per upload request?
- What happens if individual files within the batch have wildly different sizes -- does one large file block the others?
Related topics