File Handling in ASP.NET Core: Upload, Download, Validation, and Security
File handling is a common requirement in modern web applications. Users often need to upload profile pictures, documents, PDFs, spreadsheets, or other files. ASP.NET Core provides powerful tools for managing file uploads and downloads securely.
In this tutorial, you'll learn how to upload files, validate them, store them on the server, allow downloads, and follow security best practices in ASP.NET Core applications.
- What Is File Handling?
- Uploading Files
- Using IFormFile
- Saving Files to wwwroot
- Downloading Files
- File Validation
- Multiple File Uploads
- Security Best Practices
- Common Mistakes
What Is File Handling?
File handling refers to uploading, storing, retrieving, downloading, and deleting files within an application.
Common use cases include:
- User profile pictures
- Document management systems
- Resume uploads
- Invoice storage
- Product image galleries
- Content management systems
Understanding IFormFile
ASP.NET Core uses the IFormFile interface to represent
uploaded files.
public IFormFile File { get; set; }
IFormFile provides access to file properties such as:
- FileName
- Length
- ContentType
- OpenReadStream()
- CopyToAsync()
Create a File Upload Form
The first step is creating an HTML form that supports file uploads.
<form asp-action="Upload"
method="post"
enctype="multipart/form-data">
<input type="file"
name="file" />
<button type="submit">
Upload
</button>
</form>
The enctype attribute is required when uploading files.
Create the Upload Controller Action
[HttpPost]
public async Task<IActionResult>
Upload(IFormFile file)
{
if (file == null ||
file.Length == 0)
{
return BadRequest(
"No file selected.");
}
return Ok(
"File received.");
}
Save Files to the Server
Most applications store uploaded files inside the wwwroot/uploads folder.
[HttpPost]
public async Task<IActionResult>
Upload(IFormFile file)
{
if(file == null ||
file.Length == 0)
{
return BadRequest();
}
string uploadsFolder =
Path.Combine(
Directory.GetCurrentDirectory(),
"wwwroot",
"uploads");
Directory.CreateDirectory(
uploadsFolder);
string filePath =
Path.Combine(
uploadsFolder,
file.FileName);
using(var stream =
new FileStream(
filePath,
FileMode.Create))
{
await file.CopyToAsync(
stream);
}
return Ok(
"File uploaded.");
}
Generate Unique File Names
Storing files using their original names can cause conflicts.
string uniqueFileName =
Guid.NewGuid() +
Path.GetExtension(
file.FileName);
This helps prevent duplicate file names.
Validate File Extensions
Always validate file types before saving them.
string[] allowedExtensions =
{
".jpg",
".jpeg",
".png",
".pdf"
};
string extension =
Path.GetExtension(
file.FileName)
.ToLower();
if(!allowedExtensions
.Contains(extension))
{
return BadRequest(
"Invalid file type.");
}
Validate File Size
const long maxSize =
5 * 1024 * 1024;
if(file.Length > maxSize)
{
return BadRequest(
"File too large.");
}
This example limits uploads to 5 MB.
Upload Multiple Files
ASP.NET Core supports multiple file uploads.
<input type="file"
name="files"
multiple />
[HttpPost]
public async Task<IActionResult>
UploadFiles(
List<IFormFile> files)
{
foreach(var file in files)
{
// Save file
}
return Ok();
}
Create a Download Endpoint
Users often need to download files stored on the server.
public IActionResult Download(
string fileName)
{
string filePath =
Path.Combine(
Directory
.GetCurrentDirectory(),
"wwwroot",
"uploads",
fileName);
if(!System.IO.File
.Exists(filePath))
{
return NotFound();
}
byte[] bytes =
System.IO.File
.ReadAllBytes(filePath);
return File(
bytes,
"application/octet-stream",
fileName);
}
Delete Uploaded Files
string filePath =
Path.Combine(
uploadsFolder,
fileName);
if(System.IO.File
.Exists(filePath))
{
System.IO.File
.Delete(filePath);
}
Display Uploaded Images
Files stored in wwwroot can be displayed directly.
<img src="/uploads/profile.jpg"
alt="Profile Image" />
Store Files in a Database?
Small files can be stored in a database using byte arrays.
public byte[] FileData
{
get; set;
}
However, storing files on disk or cloud storage is usually more efficient.
Cloud Storage Options
Many production applications store files in cloud services.
- Azure Blob Storage
- Amazon S3
- Google Cloud Storage
- Cloudflare R2
Common File Upload Errors
- Missing enctype attribute.
- Large file sizes.
- Invalid file permissions.
- Incorrect upload path.
- Unsafe file names.
Security Best Practices
- Validate file extensions.
- Validate file size limits.
- Generate unique file names.
- Do not trust user-supplied file names.
- Scan uploaded files when appropriate.
- Restrict executable file uploads.
- Store sensitive files outside public folders.
Real-World Applications
- Profile image uploads
- Resume submission portals
- Document management systems
- Online learning platforms
- E-commerce product galleries
- Invoice and receipt storage
Frequently Asked Questions
What is IFormFile?
IFormFile is the ASP.NET Core interface used to represent uploaded files.
Can ASP.NET Core upload multiple files?
Yes. Use a List<IFormFile> parameter and the multiple attribute in the form.
Where should uploaded files be stored?
Small applications often use the wwwroot/uploads folder, while larger systems commonly use cloud storage services.
Should uploaded files be validated?
Absolutely. Validation helps protect applications from malicious uploads and excessive storage usage.
Related Tutorials
- ASP.NET Core MVC Tutorial
- Build a REST API in ASP.NET Core
- Dependency Injection in ASP.NET Core
- ASP.NET Core Middleware
- JWT Authentication in ASP.NET Core
Conclusion
File handling is an essential skill for ASP.NET Core developers. Understanding how to upload, validate, store, download, and secure files allows you to build professional web applications that safely manage user content.
By following the techniques and best practices covered in this tutorial, you can implement reliable file management features while maintaining application security and performance.