How to validate uploaded file in ASP.NET MVC?

Viewed 75246

I have a Create action that takes an entity object and a HttpPostedFileBase image. The image does not belong to the entity model.

I can save the entity object in the database and the file in disk, but I am not sure how to validate these business rules:

  • Image is required
  • Content type must be "image/png"
  • Must not exceed 1MB
5 Answers

And file length validation in asp.net core:

public async Task<IActionResult> MyAction()
{
    var form = await Request.ReadFormAsync();
    if (form.Files != null && form.Files.Count == 1)
    {
        var file = form.Files[0];
        if (file.Length > 1 * 1024 * 1024)
        {
            ModelState.AddModelError(String.Empty, "Maximum file size is 1 Mb.");
        }
    }
    // action code goes here
}
Related