Click here to Skip to main content
Email Password   helpLost your password?
Screenshot - GmailUpload.gif

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.

    /// <summary />

    /// Basic registration of events

    /// </summary />

    /// 

    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.

    /// <summary />

    /// After completing page load, call the event handler on page to perform

    /// operations on uploaded file

    /// </summary />

    /// 

    /// 

    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)
                    {
                        // do nothing

                    }
                    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 !!!

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
QuestionAJAX Script Manager conflicting with the Custom Fileupload Control
qingliu6
15:26 28 Jan '10  
Hi Shyam,

really loved your work on that file upload, Brilliant. I'm fairly new to ASP.NET. When i am using AJAX ScriptManager control which contains 2 dropdown list (changing value on the 1st drop down will change the list on the 2nd drop down) on my front page in conjunction with your script, everytime when i choose a value from the 1st drop down list, which involves a postback, and its trying to upload the image again. and if i clear the control value, the uploading image just remains there forever. How can i resolve this issue? Your help would be greatly appreciated. Thanks again for the great tool you have done. Smile

Jack
AnswerRe: AJAX Script Manager conflicting with the Custom Fileupload Control
Shyam S
20:23 28 Jan '10  
Hi Jack,

Thank you for your interest. I haven't checked your problem but I have interested a new falsh/javascript option for uploading file. You can find it at http://swfupload.org/[^]. It is a free tool and you can use it.

Best Regards,
Shyam S
GeneralGmail like file upload
Shyam S
23:00 23 Jun '09  
Gmail is using flash for uploading file. A free flash tool is available known as 'SWFUpload' which can be used to upload file like gmail manner.
Generalwhen I am working in MasterPage its not wrking
Member 4209770
21:33 12 Apr '09  
Hello,
When I am working in master page its not working. A run time error has occurred, Object is required in function.

function startCallback()
{
document.getElementById("processDiv").style.display = "block"; document.getElementById("fileName").innerText = document.getElementById("FileUpload1").value;
return true;

}

Thanks,
Sabarish
AnswerHow can I work with this file upload control and .net validation controls?
kaivanshah
20:38 19 Jan '09  
Hi All,

I have tried this file upload control it is working fine without any validations. But When I have added required field validators,regular expression validators,custom validators and validation summary in the form It's behavior is strange. As I click on submit button it is calling startCallback function so I have checked innerHTNL length of validation summary. If length =0 I am displaying progress bar.So after that it was working fine but When I click on logout button of master page validation summary length is =0 so It is displaying progress bar. So how can I handle this error as I dont want to show progress bar at that time. the problem is like when form is submitted at that time startCallback is called so can I do some change in control so I can know that which button is clicked at client side or please provide me any other solution.

Please reply me as soon as possible.

Thanks,
Kaivan Shah
Generalcomplements
Member 3767348
3:27 20 Oct '08  
Greetings Shyam,

Thank you very much for this article. i had small question regarding this upload button, can we use this upload button in the edit template of the gridview .

Regards,
Jaipal
GeneralNice article, but...
dennieku
0:15 10 Oct '08  
Nice article. It works great.
But what if I add another button to the page, which submits the main page? The form is then submitted into the IFRAME, which is not correct. Do you have a solution for this?

Thx,
Dennieku
GeneralRe: Nice article, but...
dennieku
0:16 10 Oct '08  
Sorry, I see that the post with subject "Problem with postback" handles the same problem.
I'll try to find a solution !!
GeneralThe uploaded file location
arnonzamir
15:30 3 Sep '08  
Hi,
it might sound as a dumb question, but heck -
* where is the file?! * Blush

I see the upload, but I don't know where was the file saved and how to set the location.
did I miss something very basic here?

Thanks,
- Arnon.
GeneralRe: The uploaded file location
ctembe
1:18 11 Oct '08  
Even i couldn't see the uploaded file, anywhere, in my virtual directory
How ???
QuestionProblem with postback
Member 359517
8:45 29 May '08  
Hi, thx for your article, it's great, but I have a problem and would like to see if someone can help me.

If I put the control in a page with other buttons that can do a submit, with any button I press, the last image gets uploaded again to the server.

I saw that the FileUpload control clears itself with a page postback, but that's not happening with postbacks in the sample.

Can someone help me with this?

Thanks in advance.
AnswerRe: Problem with postback
Shyam S
19:18 29 May '08  
Hi,

Thank you for your feedback. The problem is, the control registers an onsubmit statement. When page submits, by any button in that form, this code will be executed. Also the sample application will not clear the file upload control. As a quick solution, if we cear the file upload control after post back, by javascript, u can solve this problem. You can do it in completeCallback javascript function.

If this will not work in your situation, please let me know with detailed explanation of ur situation. We can make it possible Smile

Regards,
Shyam S
GeneralRe: Problem with postback
Member 4209770
4:10 13 Apr '09  
Hi,
How to clear the file upload control value, after the file uploaded to the server .(need JavaScript code).

Thanks
Sabarish
GeneralDynamically use file upload control
shahgun
0:06 28 Jun '07  
Hi shyam,
Your control works like charm and kudos for creating it. Now i had a requirement where i need to add the the file upload control dynamically. for that the form need to have enctype="multipart/form-data" . How can this be achieved in ur control?
GeneralDOTNET 2
RichardOfMercator
1:59 31 May '07  
Hi ShyamProxy,

Can I use your control to surpas the upload limit that I would normally see when using upload controls?

Is this Ajax upload button for DoTNet2 by the way and when is the Java edition coming out? I think we can really use it!!


Cheers,

RichardOfMercator
GeneralMissing the FileUploadControlTest Project
clivenyong
0:22 12 Apr '07  
Hi,
Can I have the test project as well. cause I don't know how to retrieve the file and save to the server hard disk

Thank
Yong
GeneralDon't work with UpdatePanel
dkc_project
23:08 5 Mar '07  
I placed your code into ajax UpdatePanel, and i retrieve 'AN exception occurred' exception.
I debugged it and saw that related FileUpload control doesn't have PostedFile.
GeneralRe: Don't work with UpdatePanel
shyamproxy
23:48 5 Mar '07  
Hi dkc_project,

Thanks for your feedback.

According to 'liammclennan', 'FileUpload control does not work with asynchronous postbacks, and therefore does not work from within an AJAX UpdatePanel.'. Please go to this link 'http://www.codeproject.com/useritems/simpleajaxupload.asp' for a solution. I haven't tested this control in update panel.

Thank you
Shyam
GeneralRe: Don't work with UpdatePanel
yaniar
16:09 28 Mar '07  
Yes, standard FileUpload control does not work within AJAX UpdatePanel.
If you want to upload file asynchronously within AJAX UpdatePanel, try AsyncFileUpload from http://www.arindsoft.com.
GeneralNice article....Thanks to shyamproxy
Najeed
20:30 5 Mar '07  
This is a nice article...


Last Updated 4 Mar 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010