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.