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:
.NET 8 SDK installed
Basic knowledge of ASP.NET Core Web API
Visual Studio or VS Code
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 });
}
}
Join the conversation! Your thoughts help the community grow.