Uploading a File in ASP.NET MVC3

I've done my research on this.  I've seen the literally hundreds of tutorials on how to upload a file in Microsoft's MVC platform.  So, let's do the bit that all of them show first.

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

So the first thing to note here is that this is Razor.  There isn't an HtmlHelper for a file input, so we have to add one manually.  Same for the submit button.  Then we notice that I'm using Html.BeginForm, not Ajax.BeginForm.  Everyone loves AJAX right?  Well, AJAX doesn't allow file uploads by default, so if you want to do uploads via AJAX you'll need a plugin for jquery.  I'm submitting via POST for obvious reasons, you do not want your file's byte array in your URI.  The encoding type matters here for two reasons.  First, any misspelling or incorrect case and the whole thing breaks.  Second, multipart/form-data is the only way to pass a file via a form.  Finally, you might ask why I'm passing an ID.  After all, the purpose here is just to upload the file, right?  Since this form is self-contained, we have no way to associate the file with any other data, so you need to pass some identifier of the model you're dealing with in order to make this whole thing work.  For good measure, here's what the action method should look like in the Home controller.

public ActionResult Upload(HttpPostedFileBase file, int id)

{

    // Do stuff with file  

}

This is all you need, according to those other tutorials, in order to get file uploads working.  Of course, when I put this into my project and tried to run it, I ran into something odd.  When I tried to upload a file, it went to the Upload URL, but never hit the controller action.  When I clicked upload without having selected a file, it went to the controller action, but naturally would fail.  I couldn't figure it out, so after an hour I got to the point of opening fiddler and got myself a nice clean 504 error.  Ah yes, my web.config wasn't yet allowing the larger quantity of data to pass over the wire.  I'd be upset with myself, but I was more upset with all the tutorials that ignored this obvious bit.
<httpRuntime maxRequestLength="102400"/>
That's what I was missing.  Add it to the system.web node of your web.config and the uploads won't mysteriously disappear.

Comments

Popular Posts