Upload file in C# MVC

3 August 2022

How to upload file in C# MVC project with additional validation based on content type and file size

Our simple form could be something like this:

<form action="/Home/Upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Upload File" />
</form>

And our ActionResult (with no validation):

using System.IO;
using System.Web;
using System.Web.Mvc;

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    {
        var fileName = Path.GetFileName(file.FileName);
        string folderPath = Server.MapPath("/files");

        bool folderExists = Directory.Exists(folderPath);

        if (!folderExists)
            Directory.CreateDirectory(folderPath);

        string fullPath = Path.Combine(folderPath, fileName);
        file.SaveAs(fullPath);

        return Content("Ok!");

    } else {

        return Content("Something went wrong");

    }

}

If you want to perform additional validations, for example to allow only specific content type and/or content length, here is example (only jpeg images with size less then 2MB allowed):

if (file.ContentType == "image/jpeg" && file.ContentLength < 2000000)
{
    // OK, proceed to upload ...
} else
{
    // invalid ...
}