Introduction
File upload is a very common requirement in modern web applications. Whether you are building a profile system, document management system, or image upload feature, handling file uploads efficiently is essential.
In ASP.NET Core Web API, the IFormFile interface is used to receive files sent by the client (browser, mobile app, or frontend application).
In simple words, IFormFile represents a file sent with the HTTP request. It allows you to read file data, save it to disk, or process it as needed.
In this article, we will learn, step by step, how to upload files in an ASP.NET Core Web API using IFormFile, with practical examples and best practices.
What is IFormFile in ASP.NET Core?
IFormFile is an interface in ASP.NET Core that represents a file sent with the HTTP request.
It provides useful properties and methods like:
FileName → Name of the uploaded file
Length → Size of the file
ContentType → Type of file (image, pdf, etc.)
CopyTo() / CopyToAsync() → Save file to disk or memory
Prerequisites
Before starting, make sure you have:
Step-by-Step: Upload File using IFormFile
Step 1: Create ASP.NET Core Web API Project
You can create a project using CLI:
dotnet new webapi -n FileUploadDemo
cd FileUploadDemo
Step 2: Create Upload Folder
Inside your project, create a folder named:
wwwroot/uploads
Enable static files in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseStaticFiles();
app.MapControllers();
app.Run();
Step 3: Create Model (Optional for Multiple Files)
public class FileUploadModel
{
public IFormFile File { get; set; }
}
Step 4: Create Controller for File Upload
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class FileController : ControllerBase
{
private readonly IWebHostEnvironment _environment;
public FileController(IWebHostEnvironment environment)
{
_environment = environment;
}
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest("No file uploaded.");
}
var uploadsFolder = Path.Combine(_environment.WebRootPath, "uploads");
if (!Directory.Exists(uploadsFolder))
{
Directory.CreateDirectory(uploadsFolder);
}
var filePath = Path.Combine(uploadsFolder, file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok(new { fileName = file.FileName, filePath = filePath });
}
}
Step 5: Test File Upload using Postman
Upload Multiple Files Example
[HttpPost("upload-multiple")]
public async Task<IActionResult> UploadMultiple(List<IFormFile> files)
{
var uploadsFolder = Path.Combine(_environment.WebRootPath, "uploads");
foreach (var file in files)
{
var filePath = Path.Combine(uploadsFolder, file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
return Ok("Files uploaded successfully");
}
Restrict File Size and Type
Limit File Size
if (file.Length > 5 * 1024 * 1024)
{
return BadRequest("File size exceeds limit.");
}
Allow Only Specific Types
var allowedTypes = new[] { "image/jpeg", "image/png" };
if (!allowedTypes.Contains(file.ContentType))
{
return BadRequest("Invalid file type.");
}
Save File with Unique Name (Best Practice)
var uniqueFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploadsFolder, uniqueFileName);
This prevents overwriting files with the same name.
Return File URL
var fileUrl = $"https://localhost:xxxx/uploads/{uniqueFileName}";
Common Mistakes Developers Make
Not validating file size
Not checking file type
Saving files with original names (overwriting issue)
Not handling large file uploads
Forgetting to enable static files
Best Practices for File Upload in ASP.NET Core
Always validate file size and type
Use unique file names
Store files outside project if needed (cloud storage)
Use async methods for better performance
Add proper error handling
Advanced Tip: Upload to Cloud (Azure / AWS)
Instead of storing files locally, you can upload them to cloud storage services like Azure Blob Storage or AWS S3 for better scalability and reliability.
Why File Upload is Important in Web APIs
Used in profile image upload
Document management systems
Resume upload in job portals
Media sharing applications
Summary
Uploading files in ASP.NET Core Web API using IFormFile is simple and powerful. It allows developers to handle file data efficiently, whether saving locally or processing further.
By following best practices like validation, unique naming, and proper storage, you can build secure and scalable file upload features in your .NET applications.