LESSON 11 OF 20

11. Secure File and Image Uploads

Learn how to safely upload content images in ASP.NET Core MVC with type and size validation, unique filenames, secure storage, and failure handling.

50 dk 36

Introduction

Uploading images for articles or pages is a common requirement in content management applications. However, implementing a file upload is more than adding an input type="file" element. A client-provided file name, extension, MIME type, and file content must not be treated as trusted.

In this lesson, we will use ASP.NET Core MVC and .NET 8 to implement a safer content image upload workflow. During an article create or edit operation, we will receive the file through IFormFile, validate its size and extension, avoid storing the client-provided file name, generate a unique name, and store the file outside the publicly accessible web root.

The image will later be returned through an authorized Controller action. This prevents users from accessing files directly through the physical folder structure.

The basic upload workflow

A secure upload process usually includes these steps:

  1. Submit the form using multipart/form-data.
  2. Check whether a file was provided.
  3. Apply a maximum file-size limit.
  4. Validate the allowed extensions.
  5. Treat the MIME type only as an additional, not decisive, check.
  6. Validate the file signature or content when appropriate.
  7. Generate a unique name controlled by the application.
  8. Write the file to a dedicated storage location.
  9. Store only trusted metadata and the generated name in the database.

The client-side accept="image/*" attribute improves the user experience but does not provide security. A malicious client can bypass or modify it. Therefore, every important rule must also be enforced on the server.

Designing the model and ViewModel

Instead of placing the upload field directly on the database entity, use a separate ViewModel for the operation. The following example assumes that the existing Article entity stores image information as text.

using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http;

public sealed class ArticleEditViewModel
{
    public int Id { get; set; }

    [Required, StringLength(160)]
    public string Title { get; set; } = string.Empty;

    [Required]
    public string Body { get; set; } = string.Empty;

    public string? ExistingImageName { get; set; }

    public IFormFile? Image { get; set; }
}

The ExistingImageName property can be used to display the current image on an edit page. Do not store the physical file name supplied by the user in this property. The database should contain an application-generated storage name or a file identifier.

Preparing the form as multipart

The form must use the multipart/form-data encoding type for the file to reach the Controller action. An example Razor View is shown below:

<form asp-action="Edit" method="post" enctype="multipart/form-data">
    <input asp-for="Id" type="hidden" />
    <input asp-for="Title" />
    <textarea asp-for="Body"></textarea>
    <input asp-for="Image" type="file" accept="image/jpeg,image/png,image/webp" />
    <span asp-validation-for="Image"></span>
    <button type="submit">Save</button>
</form>

Do not forget the antiforgery token. When the Tag Helpers are enabled, the MVC form Tag Helper generates a token in many standard scenarios. Still, review the project security configuration and antiforgery behavior on the action.

Validating allowed extensions and size

For this application, allow only JPEG, PNG, and WebP images. We will also limit the file to two megabytes. The extension is read from the client-provided name only for validation; the name itself will never be used for storage.

private static readonly HashSet<string> AllowedExtensions =
    new(StringComparer.OrdinalIgnoreCase)
    {
        ".jpg", ".jpeg", ".png", ".webp"
    };

private const long MaxImageSize = 2 * 1024 * 1024;

private static bool IsAllowedImage(IFormFile file)
{
    if (file.Length == 0 || file.Length > MaxImageSize)
        return false;

    var extension = Path.GetExtension(file.FileName);
    return AllowedExtensions.Contains(extension);
}

This check is not sufficient by itself. A file named with a .jpg extension may not contain JPEG data. Production applications should validate file signatures or content and, when possible, scan uploads with an antivirus or malware detection service. Never consider a file trustworthy based only on its extension.

Safe file names and a storage service

Using the client-provided FileName in a physical path can cause path traversal, overwrite, and special-character problems. Instead, generate a new name with Guid.NewGuid() or Path.GetRandomFileName(). Obtain the extension from the normalized, permitted extension.

using Microsoft.AspNetCore.Http;

public sealed class ImageStorage
{
    private readonly string _rootPath;

    public ImageStorage(IConfiguration configuration)
    {
        _rootPath = configuration["FileStorage:ImageRoot"]
            ?? throw new InvalidOperationException("Image storage path is missing.");
    }

    public async Task<string> SaveAsync(IFormFile file, CancellationToken cancellationToken)
    {
        Directory.CreateDirectory(_rootPath);

        var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
        var storedName = $"{Guid.NewGuid():N}{extension}";
        var fullPath = Path.Combine(_rootPath, storedName);

        await using var stream = new FileStream(
            fullPath,
            FileMode.CreateNew,
            FileAccess.Write,
            FileShare.None,
            bufferSize: 64 * 1024,
            useAsync: true);

        await file.CopyToAsync(stream, cancellationToken);
        return storedName;
    }
}

Reading the path from configuration makes it easier to separate development and production environments. For example, a local appsettings.json value could be:

{
  "FileStorage": {
    "ImageRoot": "C:\\AppData\\ContentImages"
  }
}

On Linux or in a container, provide the value through an environment variable. The storage directory should not be in the same tree as source code, configuration files, or compiled application files. Disable execution permissions for the directory, and do not configure the web server to expose it as a static-file directory.

Handling the upload in a Controller action

Register the storage service with Dependency Injection:

builder.Services.AddScoped<ImageStorage>();

Then perform validation and persistence in the Controller:

public class ArticlesController : Controller
{
    private readonly ApplicationDbContext _db;
    private readonly ImageStorage _imageStorage;

    public ArticlesController(ApplicationDbContext db, ImageStorage imageStorage)
    {
        _db = db;
        _imageStorage = imageStorage;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(
        ArticleEditViewModel model,
        CancellationToken cancellationToken)
    {
        if (!ModelState.IsValid)
            return View(model);

        if (model.Image is not null)
        {
            if (!IsAllowedImage(model.Image))
            {
                ModelState.AddModelError(
                    nameof(model.Image),
                    "Choose a JPEG, PNG, or WebP image no larger than 2 MB.");
                return View(model);
            }

            var storedName = await _imageStorage.SaveAsync(
                model.Image, cancellationToken);

            var article = await _db.Articles.FindAsync(
                new object[] { model.Id }, cancellationToken);

            if (article is null)
                return NotFound();

            article.Title = model.Title;
            article.Body = model.Body;
            article.ImageName = storedName;
            await _db.SaveChangesAsync(cancellationToken);
        }

        return RedirectToAction(nameof(Index));
    }
}

In a real application, delete the old image only after the new file has been saved and the database operation has completed. If the database update fails, remove the new file as a compensating action. The file system and database do not participate in one transaction, so this failure path deserves explicit design.

Serving the image securely

Because the image directory is outside the web root, return the file through an action. Instead of combining a URL value directly with a physical path, look up the article in the database.

[HttpGet]
public async Task<IActionResult> Image(int id, CancellationToken cancellationToken)
{
    var article = await _db.Articles
        .AsNoTracking()
        .FirstOrDefaultAsync(x => x.Id == id, cancellationToken);

    if (article is null || string.IsNullOrWhiteSpace(article.ImageName))
        return NotFound();

    var path = Path.Combine(_imageStorage.RootPath, article.ImageName);

    if (!System.IO.File.Exists(path))
        return NotFound();

    return PhysicalFile(path, "image/jpeg");
}

To make this example compile, expose the storage root through a controlled property or create a dedicated method that resolves a stored name. For PNG and WebP, return a trusted content type based on the stored extension or database metadata. Do not use the client-provided MIME type directly as a response header.

Failure scenarios

  • No file selected: If the image is optional, preserve the existing image. If it is required, add a ModelState error.
  • File is too large: In addition to application validation, review request-size limits in ASP.NET Core and the hosting server.
  • Unsupported extension: Return a clear error before writing anything to storage.
  • Duplicate client file name: Because the client name is not used, the risk of overwriting an existing file is reduced.
  • File saved but database update failed: Delete the orphaned file or use a cleanup process that tracks pending operations.
  • Possible malware: Keep the file in quarantine and do not make it available until scanning has completed.

Common mistakes

  • Trusting only JavaScript validation: Client-side rules can be bypassed; enforce every rule on the server.
  • Persisting the original file name: Encode it if you display it, but never use it for physical storage.
  • Putting every upload under wwwroot: Keep files that do not need public access outside the web root.
  • Assuming an extension change is enough: Consider content validation and malware scanning separately.
  • Deleting the old image immediately: If the new upload or database update fails, the article may lose its image.

Short practice exercise

Extend the article edit page with the following requirements:

  1. Change the allow-list so that only JPEG and PNG files are accepted.
  2. Set the maximum size to 1 MB and display an English validation message.
  3. Store images in a directory outside the web root.
  4. Create a secure image action that uses the article identifier.
  5. Add a cleanup method that deletes the old image after a successful replacement.
  6. Test an unsupported extension, an empty file, an oversized file, and a missing article.

Conclusion

Secure file uploading is not simply copying a file between a form and a directory. The file size, extension, content, name, storage location, and delivery mechanism must all be considered together.

In this lesson, we received a file through IFormFile, applied server-side validation, generated a unique storage name, and stored images outside the web root. You can now connect this workflow to the administration authorization, content records, and user-friendly media management features of the course project.

Sources