Introduction
Many times when we use FileUpload control, we want to upload the submitted file using AJAX behaviour, so we don't want to post all the page back to the server. Moreover, we want to show a loading image when we are uploading the file. This article discusses how we can do that.
Using the Code
So, how we can do that? First, we will create an ASPX page (FileUpload.aspx). This page will contain many controls, but the most important ones are:
- FileUpload control
- Button control
The code behind for this page will be a normal code to save the file when the button is clicked:
protected void btnUpload_Click(object sender, EventArgs e)
{
string rootFolder = ConfigurationManager.AppSettings["RootFolder"].ToString();
string fileName = rootFolder + @"ProfileName.doc";
FileUpload1.SaveAs(fileName);
pnlUpload.Visible = false;
pnlAfterUpload.Visible = true;
}
It's easy right? Well, after that, what we need is to create another page (Default.aspx). There is no code in this page. In the HTML, we will add an iframe
, the source attribute value for this iframe
is FileUpload.aspx page. We will also add an image
tag for the loading image in the HTML, as follows:
<div style="border-width:1px;border-bottom-style:solid;border-color:#F3F3F3">
<iframe id="iUploadFile" frameborder="0" src="IFrame/FileUpload.aspx">
</iframe>
<img id="imgLoading" src="Images/loading.gif" style="display:none" />
</div>
The final step now is to modify our code to show the image
and hide the iframe
when the submit button in the FileUpload.aspx is clicked, and to hide the image
and show the iframe
again when uploading the file finish. To get that, we have to add the following JavaScript functions to the (FileUpload.aspx) page:
function HideProgress()
{
parent.document.getElementById("imgLoading").style.display= 'none';
parent.document.getElementById("iUploadFile").style.display= 'block';
}
function ShowProgress()
{
parent.document.getElementById("imgLoading").style.display= 'block';
parent.document.getElementById("iUploadFile").style.display= 'none';
}
Now, all that we need is to call the ShowProgress()
function when we click the submit button. To get that, we need to set the OnClientClick
property for the button:
<asp:Button ForeColor="#FFFFFF" BackColor="#00cc00" OnClientClick="ShowProgress();"
Text="Upload Your File" ID="btnUpload" runat="server" OnClick="btnUpload_Click" />
Then we need to call the HideProgress()
function when uploading the file finish. We need to add the following line of code at the end of our code which we used to save the file in the code behind for the (FileUpload.aspx) page :
Page.ClientScript.RegisterStartupScript(this.GetType()
, @"CloseProgressbar",
@"HideProgress();", true);