How do I implement a form-based file upload with ASP.NET MVC?

Posted: (EET/GMT+2)

 

File uploads in ASP.NET MVC are handled with a simple HTML form and a controller action that accepts a file parameter. The most important part is setting the HTML form's enctype to multipart/form-data. Otherwise, the file upload won't work.

As an example, inside a CSHTML/Razor view you could do this:

@using (Html.BeginForm("Upload", "Files", FormMethod.Post, 
    new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
}

And inside the controller:

public class FilesController : Controller
{
    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Server.MapPath("~/App_Data/uploads/" + fileName);
            file.SaveAs(path);
        }

        return RedirectToAction("Index");
    }
}

Some things to note:

  • Make sure the input name matches the action parameter name (file here).
  • Use a folder like App_Data that is not directly browsable.
  • Validate the file type and size before saving.

For multiple files, use the type HttpPostedFileBase[] in your C# code and a multiple attribute on the HTML input field.