Skip to main content

FileUpload in AJAX-enabled web applications


I would like to note that this article is not about the ability to upload files to the server without the postback. There are a lot of articles on this topic, just type "AJAX FileUpload" in any search engine and you'll get many examples. However with AJAX they actually have little in common, because the XMLHttpRequest does not support asynchronous uploading of files to the server, they are rather a variety of imitations, for example, using hidden IFRAME element. Nevertheless I want to emphasize that the article is not about that but about the standard FileUpload control.
There are two problems you might encounter when using it on UpdatePanel.
Problem 1
If the postback is caused by a control which lies on the UpdatePanel, the FileUpload is always empty when it come to the server, regardless whether a file has been selected or not.
Example:
<asp:UpdatePanel ID="UpdatePanel1" runat=server>
  <ContentTemplate>
     <asp:FileUpload ID="FileUpload1" runat=server />
     <asp:Button ID="btnUpload" runat=server Text="Upload" OnClick="btnUpload_Click"/>
  </ContentTemplate>
</asp:UpdatePanel>
Solution
As XMLHttpRequest does not allow to send files asynchronously, they have to be submitted in a common manner. This problem is well described around, it is solved by registration of the control that has to submit the form as a postback trigger (in the above example it is btnUpload button).
<asp:UpdatePanel ID="UpdatePanel1" runat=server>
  <ContentTemplate>
     <asp:FileUpload ID="FileUpload1" runat=server />
     <asp:Button ID="btnUpload" runat=server Text="Upload 2" OnClick="btnUpload_Click"/>
  </ContentTemplate>
  <Triggers>
      <asp:PostBackTrigger ControlID="btnUpload" />
  </Triggers>
</asp:UpdatePanel>

Problem 2
FileUpload does not work if it is loaded not on the initial page load but appears only after asynchronous update of the page part.
Example (pnlUpload panel is invisible in the beginning and is shown after clicking on btnShowFileUpload button):
<asp:UpdatePanel ID="UpdatePanel1" runat=server>
   <ContentTemplate>
        <asp:Button ID="btnShowFileUpload" runat=server Text="Show File Upload" OnClick="btnShowFileUpload_Click"/>
        <asp:Panel ID="pnlUpload" runat=server Visible="False">
           <asp:FileUpload ID="FileUpload1" runat=server />
           <asp:Button ID="btnUpload" runat=server Text="Upload" OnClick="btnUpload_Click"/>
       </asp:Panel>
   </ContentTemplate>
   <Triggers>
        <asp:PostBackTrigger ControlID="btnUpload" />
   </Triggers>
</asp:UpdatePanel>

.......................

protected void btnShowFileUpload_Click(object sender, EventArgs e)
{
    pnlUpload.Visible = true;
}
Solution
The problem is caused by the requirement that for the normal work of FileUpload the form should have enctype="multipart/form-data". Usually, it is set in overriden OnPreRender method of FileUpload control.
protected internal override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    HtmlForm form = this.Page.Form;
    if ((form != null) && (form.Enctype.Length == 0))
    {
        form.Enctype = "multipart/form-data";
    }
}
Although during asynchronous postback this code is also executed but the form is not updated. That is why it is required to set the form content type explicitly during the first page load, for example, in the Page_Load event handler of the page or a control where FileUpload is placed.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        this.Page.Form.Enctype = "multipart/form-data";
}
In case if this task is repeated in a few places you may do a simple control derived from FileUpload with overriden OnLoad method and use it.
public class CustomFileUpload : FileUpload
{
 protected override void OnLoad(EventArgs e)
 {
     base.OnLoad(e);

     if (!Page.IsPostBack)
         this.Page.Form.Enctype = "multipart/form-data";
 }
}

Comments

Popular posts from this blog

Scrollable GridView with Fixed Headers using jQuery Plugin

Using the same example I have created a jQuery Plugin for Scrollable GridView with Fixed header so that you can directly make a GridView scrollable.   HTML Markup < form   id ="form1"   runat ="server"> < asp : GridView   ID ="GridView1"   runat ="server"   AutoGenerateColumns   =   "false"> < Columns > < asp : BoundField   DataField   =   "ContactName"   HeaderText   =   "Contact Name"   /> < asp : BoundField   DataField   =   "City"   HeaderText   =   "City"   /> < asp : BoundField   DataField   =   "Country"   HeaderText   =   "Country"   /> Columns > asp : GridView > form >   Applying the Scrollable Grid jQuery Plugin < script   src ="Scripts/jquery-1.4.1.min.js"   type ="text/javascript"> script > < script   src ="Scripts/Scro...

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...

ADO.NET Concepts With example

COMMAND OBJECT  Command object is the biggest object in ADO.NET  It is the only object which can perform actions with database  It  can be created directly using Command class or can be created using Connection.Create command (factory classes also contain creation of Command). Ex:  SqlConnection sqlCon = new SqlConnection("......");    SqlCommand sqlCmd = sqlCon.CreateCommand();  Commands that we run depend upon the kind of query that we want to execute with database. All databases support two types of queries. i. Action Queries ii. Non-action Queries Action queries are those which change the state of database and which don‟t return any query results(though they return the number of records affected). Ex: Insert, Delete and Update statements Non-action queries are those which don‟t affect the database but return the results to the user. Ex: Select statement Method of execution of queries: Command object provides the following methods to execute queries: 1. Ex...