Uploading a File with Asp.Net MVC
I’ve had to write the code for uploading a file to an MVC application quite a few times and every time I seem to struggle to find a decent example. So, future self, look no further – here is a straightforward example of how to upload a file with MVC.
Change the Form Type
The usual scenario for me is that you would like to allow the user to enter some data into a form and then choose a file to submit with this information.
According to the HTML specification the default form type (application/x-www-form-urlencoded) is inefficient for sending large amounts of binary data. We therefore need to change the form type to multipart/form-data.
Html.BeginForm("Add", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })
Save the File on the Server
ASP.Net will expose the file to us as a collection of HttpPostedFileBase objects.
var postedFile = Request.Files[0];
postedFile.SaveAs(Server.MapPath(string.Format("~/Content/{0}", postedFile.FileName)));
That’s all we need. Happy coding.