ASP.Net Ajax / File Upload Control

Posted: 08/12/2010

It's widely known that the FileUpload control does not work inside of an ASP.Net Ajax UpdatePanel. The file cannot be sent over the XML Ajax stream. The solution for this problem is to tell the button uploading the file to do a full PostBack and bypass Ajax all together. This usually works great, except for when it doesn't (hrmph). The behavior I found today was even though I was registering the control for a full PostBack (and it was doing it) the FileUpload1.HasFile always returned False and had no information about the file selected, the FIRST TIME I tried the upload button. Subsequent clicks and it would work. So the question that baffled me this afternoon was, why, when it was doing a full PostBack was the FileUpload control empty. The answer I got from a blog posted from Adam Nofsinger (from 2007) where he noticed that the first time the PostBack occured in this scenario, the form was missing “enctype=multipart/form-data”. Yikes. So Adam, if you ever read this, thanks for your post, you saved me a ton of time researching this. Here's the link to Adam's blog post, and for posterity I'm going to include some of it's contents here: http://blog.anofsinger.com/2007/10/file-upload-not-working-on-first.html

To fix this problem, add the following in your Page_Load Event:

VB

Page.Form.Attributes.Add("enctype", "multipart/form-data")

C#

Page.Form.Attributes.Add("enctype", "multipart/form-data");