Building AJAX Enabled File Uploading System with Progress Bar Using ASP.NET 2.0
 
Published: 03 Oct 2007
Abstract
This article examines how to upload a file to a remote web server using ASP.NET 2.0 and AJAX. The author also discusses how to display a "Please wait ..." message while the upload is happening.
by Jesudas Chinnathampi (Das)
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 88193/ 943

Introduction

Uploading files using ASP.NET Framework 1.0 / 2.0 / 3.0 is pretty easy. Without much error handling, all we need is a couple of lines of code to upload a file to the web server. Read my article which explains how to upload files using ASP.NET which was written four years back. AJAX is playing a greater role these days in every webpage that pops up. Uploading files using ASP.NET AJAX is not a straight forward one. Those who do know about AJAX, it is used to update some portions/sections of a web page without affecting other sections. In other words, if you do want to refresh your web page on a button click but you still want to update the content of your web page, then you should use AJAX.

In this article we will see how to upload files using ASP.NET and AJAX. We will also see how we can display a message, "Please wait … Upload in progress," during an upload is taking place. Displaying a "Wait message" always helps the user to know what is really going on; otherwise, users will have to wait and will not be sure what is going on until the upload is done. 

Common Aspects

In order to use AJAX in ASP.NET we need to have a minimum of ASP.NET 2.0 Framework and AJAX Extensions 1.0 for ASP.NET.

In order to upload a file using AJAX, we are in need of the following main Web Server controls:

1.    FileUpload Server Control

2.    Button Server Control

Apart from the above, we need to specify the usual AJAX tags ScriptManager, UpdatePanel and ContentTemplate so that during run time the ASP.NET AJAX will know which section of the web page needs to be updated.  Let us take a look at the code which uses the above:

Listing 1

<html><head>
3    <title>File Upload</title></head><body><form id="form1" runat="server">
7    <asp:ScriptManager ID="ScriptManager1" runat="server"/>
8    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
9        <ContentTemplate>
10           <asp:FileUpload ID="myFile" runat="server" />
11           <asp:Label ID="lblMsg" runat="server"></asp:Label>            
12           <asp:Button ID="btnUpload" runat="server" Text="Upload"> 
13        </ContentTemplate>
14   </asp:UpdatePanel>
15 </form>
16 </body>
17 </html>

In the above code Line 7, 8 and 9 are the ones which specify which part of this web page needs to be updated. The FileUpload control and the Button control are within the AJAX UpdatePanel control.

You might think that when the user clicks the submit button, the page will be submitted to the server. Well, this is not true. The above code will not work. The reason is that FileUpload control does not work with asynchronous post backs, and therefore does not work from within an AJAX UpdatePanel. In simple words, the FileUpload control is not posted back to the server.

Triggers

To resolve the above issue, we need to use the Trigger code block. Triggers allow us to force a post back. For an upload to happen, we need to access the FileUpload control in the server. In the following code snippet you can see how to include the Triggers block. We are invoking a PostBackTrigger. The control that will be forced to post back is “btnUpload.” Triggers block can be found in Lines 9, 10 and 11.

Listing 2

<html><head>
3    <title>File Upload</title></head><body><form id="form1" runat="server">
7    <asp:ScriptManager ID="ScriptManager1" runat="server"/>
8    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
9       <Triggers>
10           <asp:PostBackTrigger ControlID="btnUpload" /> 
11       </Triggers>
12       <ContentTemplate>
13           <asp:FileUpload ID="myFile" runat="server" />
14           <asp:Label ID="lblMsg" runat="server"></asp:Label>            
15           <asp:Button ID="btnUpload" runat="server" Text="Upload" 
OnClick="UploadFile" /> 
16        </ContentTemplate>
17   </asp:UpdatePanel>
18 </form>
19 </body>
20 </html>

The above code is now capable of doing a postback to the server. All we need is to write the usual code that we write for file upload inside the server side method UploadFile. This is the method which is invoked when the submit button “Upload” is clicked. The code will look like the following (written in C#).

Listing 3

<script runat="server">
protected void UploadFile(object src, EventArgs e)
{
    if (myFile.HasFile)
    {
        string strFileName;
        strFileName = myFile.FileName;
        myFile.PostedFile.SaveAs(Server.MapPath(".") + "//" + strFileName);
        lblMsg.Text = strFileName + " Uploaded successfully!";
    }
}
</script>
Displaying a "Please Wait …" Message during an Upload

To display the "Please Wait … Message" we need to use the UpdateProgress control. The UpdateProgress control that we will be using for our upload will be as follows:

Listing 4

<asp:UpdateProgress ID="UP" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<asp:Label ID="lblWait" runat="server" Text="Please wait.."></asp:Label>
</ProgressTemplate>                          
</asp:UpdateProgress>

Each time the submit button is clicked the web page will be posted back to the server. You would think that you will see the message, “Please wait.” Well again, we need to look at one more aspect before we can see the “Please wait” message during a file upload.

We need to write a client side JavaScript function that will change the visibility of the UpdateProgress during the post back. The JavaScript will look like:

Listing 5

<script language="javascript" type="text/javascript">
function showWait()
{
    if ($get('myFile').value.length > 0)
    {
        $get('UpdateProgress1').style.display = 'block';
    }
}
</script>

The function showWait will have to be invoked during the form submission. In our scenario that would be the OnClientClick event for the button control.

Listing 6

<asp:Button ID="btnUpload" runat="server" Text="Upload" 
OnClick="UploadFile" OnClientClick="javascript:showWait();"/>

The complete code listing for both AJAX File Upload and Please Wait message is as follows:

<%@ Page Language="C#" AutoEventWireup="true"%>
<html>
<head>
<script runat="server">
protected void UploadFile(object src, EventArgs e)
{
    if (myFile.HasFile)
    {
        string strFileName;
        strFileName = myFile.FileName;
        myFile.PostedFile.SaveAs(Server.MapPath(".") + "//" + strFileName);
    }
}
</script>
 
<script language="javascript" type="text/javascript">
function showWait()
{
    if ($get('myFile').value.length > 0)
    {
        $get('UpdateProgress1').style.display = 'block';
    }
}
</script>
    <title>File Upload</title>
</head>
<body>
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"/>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <Triggers>
            <asp:PostBackTrigger ControlID="btnUpload" /> 
        </Triggers>
        <ContentTemplate>
            <asp:FileUpload ID="myFile" runat="server" />
            <asp:Label ID="lblMsg" runat="server"></asp:Label>            
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" 
                OnClick="UploadFile" OnClientClick="javascript:showWait();"/>           
            <asp:UpdateProgress ID="UpdateProgress1" runat="server" 
                AssociatedUpdatePanelID="UpdatePanel1">
                <ProgressTemplate>
                    <asp:Label ID="lblWait" runat="server" BackColor="#507CD1" 
                        Font-Bold="True" ForeColor="White" 
                        Text="Please wait ... Uploading file"></asp:Label>
                </ProgressTemplate>
            </asp:UpdateProgress>
        </ContentTemplate>
    </asp:UpdatePanel>
</form>
</body>
</html>
Live Demo

Click the following link to upload any file to the web server. For security reasons, only text files will be allowed to upload. Please do not upload any sensitive information to the server since I am providing a hyperlink to download the file so that you can really verify that the upload happened correctly.

Upload File

Click here to download the file that you just uploaded

Downloads

Summary

So far we have seen two aspects in this article: how to upload a file using ASP.NET AJAX 1.0 extensions and how to display a please wait message during an AJAX style file upload. Both scenarios will be used very often in almost each web application. I hope you will use these techniques in your web pages.


Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 3 and 3 and type the answer here:

User Comments

Title: Thanks   
Name: Koushik
Date: 11/2/2009 6:45:20 AM
Comment:
Thanks for the solution.
Title: The trriger also not work   
Name: Vivek
Date: 10/22/2009 9:36:11 AM
Comment:
the uploader has no file when i use file uploader why???
Title: iam no sure   
Name: pedro campos
Date: 10/20/2009 4:01:10 PM
Comment:
my page do postbak every time i click upload button, why?

and i copy source code idem the example. only the page is ok, but when i insert on my page, that fail, i dont know why.
Title: Building AJAX Enabled File Uploading System with Progress Bar Using ASP.NET 2.0   
Name: Ramya
Date: 9/15/2009 3:02:25 AM
Comment:
this article is very useful. it's working fine.. Thanks a lot...
Title: Serious?   
Name: LAME
Date: 9/2/2009 12:45:12 AM
Comment:
This is the farthest thing from an async postback. Does the author even know what the heck an async postback is???
Title: Superb..   
Name: Viji
Date: 8/27/2009 12:38:54 PM
Comment:
superb...
I was breaking my head to do this..
Happy to see this post..
Lemme try this tom... :)
Title: Hmmm   
Name: VIkas
Date: 8/18/2009 3:23:06 PM
Comment:
So dude, how does it uploads files using Ajax? The upload still causes a full postback. Change the article title..
Title: Good Tutorial   
Name: Chandradev
Date: 8/5/2009 8:18:09 AM
Comment:
Hi
This is very nice tutorial. But while implementing in master page. It is giving so error. And while keeping .gif image inside progress template. It is not rotating. What is the problem ?
Title: Great stuff!   
Name: Stefania
Date: 7/23/2009 4:28:28 AM
Comment:
Thank you, excellent article.
Title: Appreciate   
Name: Asher Mehboob
Date: 7/6/2009 6:02:37 AM
Comment:
Thank you for this article. helped alot.
Title: Thank You Thank You   
Name: Chris
Date: 6/19/2009 12:41:10 PM
Comment:
Thank you for the article. I'm a novice and have been researching this on and off for a week. Everything I found was way overcomplicated for what I need. This is perfect.

Thanks
Title: Nice   
Name: Jorge Bautista
Date: 6/18/2009 11:19:54 PM
Comment:
Thank you so much, it was really helpful!
Title: Greate Programming   
Name: amit Kumar Jha
Date: 6/5/2009 7:04:11 AM
Comment:
I would like to thank a lots to develop such great program in simple way. Really it helped me. I found all thing relted FileUploading in this development.
Title: Very Helpful   
Name: Preeti
Date: 5/21/2009 1:18:56 AM
Comment:
very helpful........
helped me a lot....
Thanks
Title: Good article, but..   
Name: Harish Chandra
Date: 5/15/2009 4:10:06 AM
Comment:
I want progress bar when file uploading take place and progress bar will grow as how much data uploaded (in size).
harishmohank@rediffmail.com
Title: good article   
Name: Arathy
Date: 5/8/2009 4:46:10 AM
Comment:
Hi,

really good article.....thank alot guys..
Title: masterPage-not working   
Name: Tom
Date: 5/6/2009 5:25:20 AM
Comment:
Hi,good article!!!But did someone find a way to working with Master Page?
Title: count show   
Name: sushil
Date: 4/20/2009 9:06:15 AM
Comment:
Good article!!! I wonder how can the count can be incremented in progress bar?
Say for example I am uploading an exel file having 100 data, I want to show the count in progress bar like "x data uploaded". Here x will vary from 1 to 100. Thanks!
Title: really helpfull   
Name: ram
Date: 4/10/2009 1:36:16 PM
Comment:
Very Good Article Thanks
Title: Can't upload to hosted server   
Name: Larry
Date: 3/29/2009 6:38:22 PM
Comment:
I can't understand how this could work since it just saves the file to the server. If you're on a hosted server then there's no way you can load a file to it. What I want is to be able to save the file in the database on the server. However, all attempts have failed with a "Request for the permission of type 'System.Security.Permissions.FileIOPermission" error.

By the way, you can't do a file upload without a full postback according to the literature out there, so that's not why you use the updatepanel. You use it for other aspects of the file upload process.
Title: Display message does not show   
Name: joar
Date: 3/11/2009 5:04:45 AM
Comment:
I was happy to see your solution, but as often happens, solutions doesn't always function....for me
Title: Not working   
Name: mab
Date: 2/27/2009 9:26:28 AM
Comment:
hi... this is good job! but this code not working with master page!!!
Title: My 'please wait' doesnt show   
Name: Pinch
Date: 2/18/2009 4:41:12 PM
Comment:
My 'please wait' doesnt show, but it does upload, any ideas? thanks, list@paulharr.com
Title: So   
Name: chawelson
Date: 2/12/2009 4:03:25 AM
Comment:
Lemmie try this out
Title: Hmmm   
Name: Danieö
Date: 1/13/2009 9:36:05 AM
Comment:
What's the the purpose of using an updatepanel here? You're still doing a full postpack, so why not use a div to show/hide the label?
Title: Good!! It worked for me   
Name: Mukesh
Date: 11/24/2008 11:32:12 AM
Comment:
Hi! It worked for me..Thanks a lot..
Title: Problem with code   
Name: Preeti
Date: 10/14/2008 2:07:34 AM
Comment:
this code is good but it doesn't work for large size files
Title: Building AJAX Enabled File Uploading System with Progress Bar Using ASP.NET 2.0   
Name: deva
Date: 9/16/2008 10:24:33 AM
Comment:
update progress is not working and first time not upload to server, second time we upload any file, then only upload that file.
This code not working in VS2005.
Title: hi   
Name: bahador
Date: 9/11/2008 7:21:21 AM
Comment:
hi freid
thanks alot fot your article
Title: very nice   
Name: mehmet
Date: 9/10/2008 4:54:18 AM
Comment:
very very thanks...
very good work
Title: Building AJAX Enabled File Uploading System with Progress Bar Using ASP.NET 2.0   
Name: Neeraj k Shrivastwa
Date: 8/6/2008 6:34:51 AM
Comment:
The FileUpload Server Control does not work within the UpdatePanel. Within the updatepanel the HasFile property of FileUpload control always comes false.
Title: Super   
Name: MMK
Date: 8/5/2008 5:59:43 AM
Comment:
useful
Title: No Progress Bar   
Name: Nic
Date: 7/23/2008 8:12:42 AM
Comment:
There is no progress bar here so the title is even more misleading...
Title: Feedback   
Name: Meera
Date: 7/1/2008 2:41:11 AM
Comment:
Can this be done in a user control???
Title: hi   
Name: jeni
Date: 6/9/2008 4:10:17 AM
Comment:
its helpfull
Title: Good Code   
Name: Naresh
Date: 6/5/2008 9:49:13 PM
Comment:
Very clear saving me from lot of confusion...
Title: PostBackTrigger ???   
Name: AL
Date: 5/16/2008 7:11:44 AM
Comment:
What reason put this in UpdatePanel if you use PostBackTrigger? This is full PostBack!
Title: Good Code   
Name: Rahi
Date: 5/14/2008 4:56:31 PM
Comment:
Saved me a lot of time...
Title: Have to agree with the new guy   
Name: Blake Shadle
Date: 4/10/2008 9:18:53 AM
Comment:
I'm going to have to agree with the new guy on this one. Not exactly the "AJAX" experience that I'm sure everyone hoped for.
Title: error when in UserControl   
Name: Exshakto
Date: 4/3/2008 6:03:27 AM
Comment:
Im trying to put this in a asp.net User Control, and im getting an error in the javascript. Where do you think I should put the javascript when its in a user control?
Title: cool   
Name: Sudhir T
Date: 3/10/2008 8:07:34 AM
Comment:
Nice post. Simple and beautiful
Title: great!!!!!!!!   
Name: sadhana singh
Date: 2/27/2008 9:58:15 PM
Comment:
very nice please keep on pasting more materials it helped me lot thx again!!!!!!!!!
Title: Postback is happening   
Name: Nagaraj
Date: 2/1/2008 5:41:17 AM
Comment:
Still postback is happening when we upload file.
Title: The title is misleading!!!   
Name: MCM
Date: 1/18/2008 3:10:43 PM
Comment:
This is NOT AJAX. It just doing a full post back. If it's just post back without utilizing any AJAX...why would you need to put it into an update panel?
Title: Very Good Ariticle   
Name: Rahul Chauhan
Date: 1/7/2008 1:52:32 AM
Comment:
Plz keep on posting new tutorials on ajax.

Great Job
Title: Good   
Name: Rajak Shaik
Date: 12/14/2007 12:06:31 AM
Comment:
Very good article
Title: How to upload the media   
Name: Cristiano
Date: 12/12/2007 8:37:19 AM
Comment:
How to upload some media like mp3 songs and picture .jpeg
Title: Need attachment in Sharepoint Designer Form   
Name: Kuldeep Singh
Date: 12/10/2007 6:27:55 AM
Comment:
Would you please explain how can i use this code in my Sharepoint Designer custom form????
Title: .NET Programmer   
Name: Raj
Date: 12/3/2007 12:13:15 PM
Comment:
Awesome buddy, although simple it made my day today. Superb.
Title: Misleading Title   
Name: Haissam Abdul Malak
Date: 11/30/2007 2:11:36 AM
Comment:
The article is explained in a good way, however the content is not related to the title!!
Title: hail to the n00bz   
Name: Michael
Date: 11/15/2007 8:00:39 AM
Comment:
Great article, thanks ;)
:) Although I'm using this for my current project:
http://www.aurigma.com/Products/ImageUploader/default.aspx
The price is pretty steep though but it has yummy resize and thumbnailing along with other stuff that I don't need :)
Title: one more developer   
Name: Dotnet Coder
Date: 11/14/2007 4:46:45 PM
Comment:
Even though you are using UpdatePanel. It is not actually AJAX, it is posting synchronously all the time.
Title: How to change postedFile?   
Name: nice
Date: 11/13/2007 8:33:45 PM
Comment:
How to change (in code) myFile.PostedFile in UploadFile() method? Changing it u can steal any file form client hard drive :-)
Title: good   
Name: iraj
Date: 11/13/2007 2:44:49 PM
Comment:
great
Title: URL   
Name: JasonJ
Date: 11/13/2007 11:56:48 AM
Comment:
Here is the link.

http://geekswithblogs.net/rashid/archive/2007/08/01/Create-An-Ajax-Style-File-Upload.aspx
Title: Cheating   
Name: JasonJ
Date: 11/13/2007 11:55:45 AM
Comment:
This method simply fakes an ajax postback and which might look cool but defeats the whole purpose of the ajax postback. Anyway, here is a link to a page that does it correctly, using an IFrame as Microsoft does in Hotmail.
Title: FileUpload AJAX   
Name: Subgurim
Date: 11/13/2007 5:32:20 AM
Comment:
Great, but take a look at the FileUpload AJAX control for ASP.NET hosted on codeplex (http://www.codeplex.com/fileuploadajax)
Title: Update Panel not working in side from view   
Name: QuocThinh
Date: 10/8/2007 2:58:54 AM
Comment:
Hi all, I just try your method, but I have a form view all the field will be save to the database, among that, I have fileUrl file that contains the uploads filename, so I must put this upload file inside the form view. But it not working both update panel and update progress, I don't know why.
Title: Not working with gif IE7 solved   
Name: lp
Date: 10/4/2007 10:46:25 AM
Comment:
Sorry for the 3rd comment ;-) but I've found solution for IE7 here http://west-wind.com/WebLog/posts/1227.aspx:

add this to JavaScript:
setTimeout('document.images["Progressbar"].src = "progressbar_green.gif"', 200);

and set ID of the image to "Progressbar".
Title: Not working with gif   
Name: lp
Date: 10/4/2007 10:01:27 AM
Comment:
In FF it's working, IE7 and Opera not :-(
Title: Not working with gif   
Name: lp
Date: 10/4/2007 9:47:28 AM
Comment:
Thx for the article.

But I got a problem. Text (Label) is working OK but using gif e.g. from http://mentalized.net/activity-indicators/ doesn't work - it shows only a white place. Any idea?
Title: This is NOT a AJAX based File Upload Method   
Name: Adam Nemitoff
Date: 10/3/2007 10:32:54 AM
Comment:
The method documented here does a full post-back and therefore the title of this article is misleading!
Title: why?   
Name: Mikal Schacht Jensen
Date: 10/3/2007 3:46:46 AM
Comment:
I've been attempting to upload files using ASP.NET ajax, and although I haven't spent much time exploring it, I always ended up having to do a full postback to actually be able to retrieve the file serverside. So when I first saw this article linked somewhere, I immediatly clicked over here.

I'm still a fairly inexperienced programmer with less than a year's paid programming under my belt. But having read it now, I fail to see the point of it all. Doesn't adding the button to a postbacktrigger make it cause a full postback, and thus defeat the entire purpose of using Ajax?
Title: Rc   
Name: rahul
Date: 10/3/2007 2:33:35 AM
Comment:
good, but not explored ajax much






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2009 ASPAlliance.com  |  Page Processed at 11/7/2009 3:57:44 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search