Thursday
Sep162010
MVC2 - File upload with HttpPostedFileBase
Thursday, September 16, 2010 at 2:50AM
ASP.NET MVC2 makes it extremely easy to upload a file to your controller.
Scott Hanselman blogged about this in detail
The article is a bit dated, so there are a few small tweaks for MVC 2.
View
<% using(Html.BeginForm("Upload CSV", "Customer", FormMethod.Post, new { enctype = "multipart/form-data" })){ %> <%: Html.ValidationSummary() %> <input type="file" id="fileUpload" name="fileUpload"/> <input type="submit" value="Upload file" /> <% } %>
- You need to use FormMethod.Post
- You need to make sure encoding type is multipart/form-data - otherwise the server will not receive anything!
- ValidationSummary isn't really needed, but you might want some place to throw up some errors.
- The name of the input type="file" needs to match the argument in the controller, in my case "fileUpload"
Controller
[HttpPost]
public virtual ActionResult UploadCustomer(HttpPostedFileBase fileUpload)
{
if (fileUpload == null)
{
// problem
return;
}
if (fileUpload.ContentLength == 0)
{
// problem
return;
}
var reader = new StreamReader(fileUpload.InputStream);
- The binder will automatically take the uploaded file and stick it in the HttpPostedFileBase class.
- You can check it's status, and then grab the InputStream and read (and write out) the stream if you need to.
Gotchas
Some AJAX libraries sometimes like to hijack a Form submit. In our case, it was turning the multipart/form-data back to application/x-www-form-urlencoded - which will not work.
If fileUpload remains null in the controller, check your Request object on the controller and see what's the encoding used on the post back.





Reader Comments (6)
Thanks for explaining that the names had to match! I was pulling my hair out until I read that!
Thanks John,
It is a great help !!
noce work done !!
Thanks again !
I'm having an issue with the HttpPostedFile uploading .docx files correctly.
Have you come across this issue before?
I'm not sure what specific problem are you seeing. Is your controller being called? Is the argument null?
Hi,
Even in my case also, it iss converting the multipart/form-data back to application/x-www-form-urlencoded. what will be the solution
Specify enctype=multipart/form-data in your < form > element