ASP.NET FleUpload control doesn't work properly under Ajax

ASP.NET FileUpload control doesn't work when placed in ASP.NET Ajax UpdatePanel control. If you try to upload a file, PostedFile property is always null. That means you won't be able to access the file from your code.

There is a simple solution to this problem - you have to enable full post back. You can place FileUpload control and/or upload button outside the UpdatePanel, or (what is better) to add PostBackTrigger in UpdatePanel that will perform a full post back on upload button click.

<asp:UpdatePanel ID="AjaxUploader" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </ContentTemplate>
    <Triggers>
        <asp:PostBackTrigger ControlID="btnUpload" />
    </Triggers>
</asp:UpdatePanel>

There is one more solution - to use 3rd party FileUpload control. I found excellent FIle Upload Ajax open source control that can work under Ajax.

"FileUploadAJAX is an open source ASP.NET 2.0 custom control that is similar to the predefined FileUpload control but with a key difference: AJAX behavior And what does this means? This means that with the FileUploadAJAX we can upload files in an asynchronous way and without reloading the page... that's all!"

To use FileUpload Ajax control, drag it on a form

<cc1:fileuploaderajax id="FileUploaderAJAX1" runat="server" maxfiles="5" />

In code behind, usage is also very simple (sample taken from FileUpload Ajax website)

protected void Page_Load(object sender, EventArgs e)
{
    if (FileUploaderAJAX1.IsPosting)
        this.managePost();
}

private void managePost()
{
    HttpPostedFileAJAX pf = FileUploaderAJAX1.PostedFile;
    if (pf.ContentType.Equals("image/gif") && pf.ContentLength <= 5 * 1024)
        FileUploaderAJAX1.SaveAs("~/temp", pf.FileName);
}

You can download the control and try it live on fileuploadajax.subgurim.net

Enjoy not having problems with FileUpload control!

AddThis Social Bookmark Button

Published Thursday, March 13, 2008 9:34 PM by janko
Filed under:
Powered by Community Server (Commercial Edition), by Telligent Systems