ASP.NET Core  

How to Upload File in ASP.NET Core

File upload functionality is one of the most common requirements in modern web applications. Whether users are uploading profile pictures, documents, PDFs, Excel files, or images, handling file uploads securely and efficiently is essential.

ASP.NET Core provides built-in support for file uploads using the IFormFile interface. In this article, we will learn how to upload files in ASP.NET Core step by step, including how to save them to the server safely.

Why File Upload Is Important

File uploading is widely used in:

  • Profile image uploads

  • Resume submission forms

  • Document management systems

  • Invoice and report uploads

  • E-learning platforms

  • Admin dashboards

Because it is used in almost every business application, understanding file upload in ASP.NET Core is a must for developers.

Understanding I form file in ASP.NET Core

In ASP.NET Core, uploaded files are represented using the IFormFile interface. This interface provides access to:

  • File name

  • File size

  • File content type

  • File content stream

When a form is submitted with enctype="multipart/form-data", ASP.NET Core automatically binds the uploaded file to an IFormFile parameter.

Method 1: Basic File Upload and Save to Server

Let’s create a simple API endpoint that allows users to upload a file and save it inside a folder on the server.

Controller Code

using Microsoft.AspNetCore.Mvc;

[ApiController]

[Route("api/[controller]")]

public class FileUploadController : ControllerBase

{
    [HttpPost("upload")]

    public async Task<IActionResult> UploadFile(IFormFile file)

    {
        if (file == null || file.Length == 0)

            return BadRequest("No file selected.");

        var folderPath = Path.Combine(Directory.GetCurrentDirectory(), "Uploads");

        if (!Directory.Exists(folderPath))

            Directory.CreateDirectory(folderPath);

        var filePath = Path.Combine(folderPath, file.FileName);

        using (var stream = new FileStream(filePath, FileMode.Create))

        {

            await file.CopyToAsync(stream);

        }

        return Ok("File uploaded successfully.");
    }
}

How This Works

  • The file is received as an IFormFile parameter.

  • We check whether the file exists.

  • We create an Uploads folder if it does not exist.

  • The file is saved using FileStream.

  • A success message is returned.

This is the simplest and most common way to upload files in ASP.NET Core.

Method 2: Secure File Upload with Validation (Recommended)

In real-world applications, simply saving files is not enough. We must validate:

  • File size

  • File type

  • Duplicate file names

  • Security risks

Here is a more secure version:

[HttpPost("secure-upload")]
public async Task<IActionResult> SecureUpload(IFormFile file)

{

    if (file == null || file.Length == 0)
        return BadRequest("No file selected.");

    // Limit file size (example: 2MB)
    if (file.Length > 2 * 1024 * 1024)
        return BadRequest("File size exceeds limit.");


    // Allow only specific extensions

    var allowedExtensions = new[] { ".jpg", ".png", ".pdf" };
    var extension = Path.GetExtension(file.FileName).ToLower();

    if (!allowedExtensions.Contains(extension))

        return BadRequest("Invalid file type.");

    var fileName = Guid.NewGuid().ToString() + extension;
    var filePath = Path.Combine("Uploads", fileName);

    using (var stream = new FileStream(filePath, FileMode.Create))

    {
        await file.CopyToAsync(stream);
    }

    return Ok("File uploaded securely.");
}

Why This Method Is Better

  • Prevents large file attacks

  • Blocks unauthorized file types

  • Prevents file name conflicts

  • Uses unique file names

  • More secure for production

This is the recommended approach for real-world applications.

Important Security Best Practices

When implementing file uploads, always:

  • Validate file size

  • Restrict file extensions

  • Rename uploaded files

  • Avoid executing uploaded files

  • Store files outside wwwroot if possible

  • Use antivirus scanning for sensitive systems

  • Security is critical when handling file uploads.

HTML Form Example (Frontend)

To upload files from a form:

<form method="post" enctype="multipart/form-data" action="/api/FileUpload/upload">

    <input type="file" name="file" />
    <button type="submit">Upload</button>

</form>

The key requirement is:

enctype="multipart/form-data"

Without this, file upload will not work.

Real-World Use Cases

File upload functionality is essential in:

  1. HR systems (resume uploads)

  2. School portals (assignment submission)

  3. Banking apps (document verification)

  4. E-commerce sites (product images)

  5. Healthcare systems (report uploads)

Because almost every enterprise application requires file upload, this topic has strong long-term search value.

Common Interview Questions

  • What is IFormFile in ASP.NET Core?

  • Why do we use multipart/form-data?

  • How do you restrict file size?

  • How do you prevent malicious file uploads?

  • Where should uploaded files be stored?

Understanding these concepts improves backend development skills significantly.

Conclusion

Uploading files in ASP.NET Core is simple using the IFormFile interface. However, secure file handling requires validation, size limits, file type restrictions, and safe storage practices.

The two key approaches are:

  1. Basic file upload and save

  2. Secure file upload with validation (recommended)

For production applications, always implement proper validation and security measures.

Mastering file upload functionality is essential for building professional ASP.NET Core applications.