Friday, January 18, 2008

HttpFileCollection Always Zero 

I ran into and interesting problem recently trying to get an AJAX style file upload working with an HttpHandler. The HttpFileCollection (Request.Files) was always empty with a count of zero.
(Request.Files == 0) == true

I was using the AjaxFileUpload, a jQuery plug-in intended to be paired with PHP, but compatible with any server side handler. Since I use ASP.NET, I wrote an HttpHandler to receive the form post, save the file on the server, and send a JSON response.

Without investigating too closely, it looks like the AjaxFileUpload creates an iframe, moves the html file input into the iframe and submits it to specified handler. I didn't want to user "runat='server'" controls so I just put a plain html input tag in the page like so.

<input type="file" id="AjaxFileInput" />

I ran my project and everything seemed to be working and submitting, fine, but the HttpFileCollection always had a count of 0.

I created a simple page with no ajax that posted back to itself to test the plain HTML inputs, and the Request.Files collection was still empty. I tried adding the "runat='server'" attribute and it suddenly worked, of course. I didn't want to user server controls, because I wanted to add new inputs as needed with client script.

It seemed like the Request.Files collection would only be populated if I used the ASP.NET server controls, but I could not think of any reason why. Finally, I looked at the code rendered by the server controls and discovered the answer.

Every site I found said there were 2 things you needed to get the HttpFileCollection to populate.

1) Make sure the form method is "POST"
2) Make sure the form enctype is "multipart/form-data"

The AjaxFileUpload code dutifully had this right, however there is one more thing that ASP.NET needs.

3) The HTML file input must have a "name" attribute.

Here is a final sample of an accurately constructed plain HTML form that will populate the Request.Files collection.

<form action="" method="POST" name="form1" id="form1" enctype="multipart/form-data">
    <input type="file" id="AjaxFileInput" name="AjaxFileInput" />
</form>


This seems like a bug, to me, and I don't know if .NET 3.0-5 fixes this. This document does not reflect what I have found to be true.

This page is powered by Blogger. Isn't yours?