AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1442&pId=-1
Building AJAX Enabled File Uploading System with Progress Bar Using ASP.NET 2.0
page
by Jesudas Chinnathampi (Das)
Feedback
Average Rating: 
Views (Total / Last 10 Days): 81714/ 66

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.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 4:10:03 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search