Make the ASP.Net FileUpload control work inside the UpdatePanel control


Today I hit an age-old problem whereby if the FileUpload control is used within an UpdatePanel, when the partial-postback completed, the FileUpload.HasFile property always equates to False.  There are absolutely hundreds of pages online providing some kind of solution, but most are totally hideous.

Show me the easy way!

These two things are all you need, and both are done in code-behind - no need to hack your HTML!

Step 1: Force the form to submit binary data

In Page_Load, configure the form to submit multipart/form-data.  By default, forms submit encoded text, and this property is set automatically in ASP.Net.  However, when using an UpdatePanel control, the property never gets set.  Its a bug really (I'm sure there's some weird and wacky reason it doesn't happen):

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        ' whatever... '
    End If
    Page.Form.Attributes.Add("enctype", "multipart/form-data") ' force the form to submit multipart MIME data streams (e.g. raw file data!) '
End Sub

Step 2: Buttons/LinkButtons must cause a full postback (not partial)

Whatever button(s)/linkbutton(s) would usually trigger a partial page postback (e.g. whenever you want the file to be uploaded), these controls must cause a full page postback.  You can do this in Page_Load if you want, but I usually do it in Pre_Render as I add other logic (JQuery etc.) to my controls based on their visibility.  By doing this step last, you can be assured no other page code will affect the result:

Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
End Sub

Step 3: Beer*

Job done, and no messing about with HTML-side triggers and all that nonsense!  Time for a beer.

* Please note that step 3 is not compulsory.  I don't endorse drunkeness...


Posted by TonyO on 24/06/2016

Such a simple answer

Posted by Sumit satpute on 13/12/2017

thanks Its Work for me

New Comment

This is to prove that you are not a spam robot posting links to dodgy sites!