Introduction
This is an inherited button control which can perform file upload like in gmail manner. The button uses the inherited IFRAME
technique to avoid full page rendering so that user will get a nice experience.
Background
I have searched for an article to perform GMail like file upload. It seems that we cannot perform file uploading using AJAX. I got some nice javascript from webtoolkit which was written to operate with PHP. The script uses the hidden IFRAME
technique. Here I have created an derived ASP.NET Button control which can perform the trick.
Using the code
To open the project, unzip it and open the file FileUploadControlTest.sln Open the file UploadButton.cs. The OnInit
method will register the LoadComplete
event, include the javascript which is a web resource (for more information on webresource click here), and sends the onsubmit
statement to client.
protected override void OnInit(EventArgs e)
{
this.Page.LoadComplete += new EventHandler(Page_LoadComplete);
base.OnInit(e);
this.Page.ClientScript.RegisterClientScriptInclude(this.GetType(),
"ScriptBlock",
this.Page.ClientScript.GetWebResourceUrl(this.GetType(),
"WebControls.JScripts.AIMScript.js"));
string onsubmitstatement = "return AIM.submit(document.forms[0],
{'onStart' : " + OnStartScript + ",
'onComplete' : " + OnCompleteScript + "})";
this.Page.ClientScript.RegisterOnSubmitStatement(this.GetType(),
"OnSubmitScript", onsubmitstatement);
}
The onsubmit
script creates a new hidden IFRAME
in the dom and sets the target
of the form to this IFRAME
. So the section the user is seeing will not get redrawn after postback. In the Page_LoadComplete
event of the page, we will get the FileUpload control filled with the uploaded file. We will call the event handler in the Page_LoadComplete
method. The return text after executing the event handler will be returned to the client.
void Page_LoadComplete(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (this.Parent.FindControl(RelatedFileUploadControlId) != null)
{
FileUpload fu =
this.Parent.FindControl(RelatedFileUploadControlId) as FileUpload;
UploadButtonEventArgs args = new UploadButtonEventArgs(fu);
UploadButtonEventHandler handler =
(UploadButtonEventHandler)Events[EventUploadClickKey];
if (handler != null)
{
try
{
WriteTextToClient(handler(this, args));
}
catch (System.Threading.ThreadAbortException ex)
{
}
catch (Exception ex)
{
WriteTextToClient("An exception occurred - " +
ex.Message);
}
}
else
{
WriteTextToClient("Handler not registered");
}
}
}
}
In the onload
method of IFRAME
, we will call the function registered as OnCompleteScript
, and pass the text inside the IFRAME
which is the response text.
Points of Interest
The hidden IFRAME technique is an old one but in some complex situations, it will help us !!!