« Silverlight GeocodeLocation SerializationException when calling RouteService CalculateRoute | Main | VB.NET - there are times when you have to keep an open mind »
Thursday
Sep162010

MVC2 - File upload with HttpPostedFileBase

 

ASP.NET MVC2 makes it extremely easy to upload a file to your controller. 

Scott Hanselman blogged about this in detail

http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

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!

November 12, 2010 | Unregistered CommenterMonica

Thanks John,

It is a great help !!

noce work done !!

Thanks again !

July 6, 2011 | Unregistered CommenterPriyank

I'm having an issue with the HttpPostedFile uploading .docx files correctly.
Have you come across this issue before?

October 24, 2011 | Unregistered CommenterSteven Boy

I'm not sure what specific problem are you seeing. Is your controller being called? Is the argument null?

November 2, 2011 | Registered CommenterJohnLiu.NET

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

January 3, 2012 | Unregistered CommenterShruti

Specify enctype=multipart/form-data in your < form > element

January 9, 2012 | Registered CommenterJohnLiu.NET

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>