WorldofASP.NET : ASP.NET Tutorial, Hosting, and Source Code
You are 1 of 6788 users

WorldofASP.NET >> ASPNET >> Applications

File Upload with AJAX.NET Progress Bar

File Upload with AJAX.NET Progress Bar using ScriptManager and UpdatePanel

Published Date : 28 Feb 2008

Author : Majid Malik
Language : C#
Platform : .NET
 
Technology : ASP.NET
Views : 3981
Rating : (1 votes so far)
Email to a Friend | Print this Article | Add to Favourites | Report Error

Introduction

In this short article I will try to explain how to show, during a File Upload,
a Progress Bar using AJAX.NET Web Server Controls
ScriptManager and UpdatePanel.

Background

This demo/sample involves an HTTPModule which is used to intercept the uploaded file.
This interception operation off-loads the file data chunck by chunck and
enables a Progress Bar as well as enables virtually unlimited file sizes in the upload.

Using the code

1) Download the file Upfilesbe.zip
2) Unzip to any directory
3) Copy the Upfilebe folder to wwwroot directory.
4) View the aspx page samples\CS\uploadsamples\Advanced\UploadWithAjaxProgress \uploadwithAjaxNETprogress.aspx in the browser.
5) Everything is all setup and ready to go.

The aspx source can be viewed in the file uploadwithAjaxNETprogress.aspx.
<br> 
The following code snippet is from the codefile
uploadwithAjaxNETprogress.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using expandata.net;


public partial class samples_CS_uploadsamples_Advanced_UploadWithAjaxProgress_uploadwithAjaxNETprogress 
    : System.Web.UI.Page
{
    // This field is visible in the javascript code being used in the aspx file. It is required by the HTTPModule
    protected string ProgID = "";



    // On Page_Load event we create a new ProgresID by calling the GenerateProgressID() method.
    // After that we store this value in the session object for later use.
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!this.IsPostBack)
        {
            // GenerateProgressID
            GenerateProgressID();

            //store ProgID in Session["PROGRESSID"]
            Session["PROGRESSID"] = ProgID;

            //Remove "CANCELLED" object from Session
            Session.Remove("CANCELLED");
        }
    }
    
    
    //// <SUMMARY>
    /// ////////////////////////////////////////
    /// </SUMMARY>
    private void GenerateProgressID()
    {
        // create NextProgressID and assign it to global variable ProgID
        // DNUpFilesBE class is in the expandata.net assembly
        ProgID = (new DNUpFilesBE()).NextProgressID();
    }


    protected void ButtonUpload_Click(object sender, System.EventArgs e)
    {
        // disable ButtonUpload
        this.ButtonUpload.Enabled = false;

        //ProcessUpLoad();
        ProcessUpLoad();
    }


    /// <SUMMARY>
    /// /////////////////////////////////
    /// </SUMMARY>
    void ProcessUpLoad()
    {
        // create DNUpFilesBE object
        expandata.net.DNUpFilesBE dnUpFilesBE = new expandata.net.DNUpFilesBE();

        // DNFileBE object
        expandata.net.DNFileBE dnFileBE;

        try
        {
            // set CacheFolder
            dnUpFilesBE.CacheFolder = Server.MapPath((string)Application["vroot"]) + "/Cache";

            //set DestinationFolder
            dnUpFilesBE.DestinationFolder = Server.MapPath((string)Application["vroot"]) + "/Dest";

            // ProcessRequest
            dnUpFilesBE.ProcessRequest(this.Request);

            // Display Results
            if (dnUpFilesBE.Files.Count > 0)
                LabelTitle.Text = "&lt;DT><B>All files have been successfully processed by UpFilesBE!!</B>";
            else
                LabelTitle.Text = "&lt;DT><B>No files have been submitted to UpFilesBE!!</B>";

            LabelSaveInfo.Text = "";

            System.Text.StringBuilder saveInfo = new System.Text.StringBuilder();

            //walk through the files collection
            for (int i = 0; i < dnUpFilesBE.Files.Count; i++)
            {
                dnFileBE = dnUpFilesBE.Files[i];

                if (i != 0)
                {
                    saveInfo.Append("&lt;DD> ");
                    saveInfo.Append("&lt;DT>----------------------------------------");
                }

                saveInfo.Append("&lt;DT><B>File Number (" + ((i + 1).ToString()) + ")" + "&lt;/B>");
                saveInfo.Append("&lt;DD> ");

                if (dnFileBE.Size == 0)
                {
                    LabelTitle.Text = "&lt;DT><B>Some files could not be processed by UpFilesBE!!</B>";
                    saveInfo.Append("&lt;DT>Please enter a valid filename to upload;");
                }
                else if (dnFileBE.Size > 0)
                {
                    //set Overwrite to true;
                    dnFileBE.Overwrite = true;

                    // call Save();
                    dnFileBE.Save();

                    // check savedresults
                    switch (dnFileBE.Processed)
                    {
                        //case dnSaved:
                        case dnSaveResultsEnum.dnSaved:
                            //--- File Name
                            saveInfo.Append("&lt;DT>File name::<DD> " + dnFileBE.Name + "");
                            //--- Form File Field Name
                            saveInfo.Append("&lt;DT>Form File Field name::<DD> " + dnFileBE.FormName + "");
                            //--- dnSaveResultsEnum, file save status code
                            saveInfo.Append("&lt;DT>File Save result of type dnSaveResultsEnum::<DD> " + dnFileBE.Processed + "");
                            //--- Full path of the file as it appears on the client
                            saveInfo.Append("&lt;DT>Full path of the file as it appears on the client::<DD> " + dnFileBE.ClientPath + "");
                            //--- Full path of the file as saved in thge destination folder on the server
                            saveInfo.Append("&lt;DT>Full path of the file as saved in the destination folder on the server::<DD> " + dnFileBE.DestinationPath + "");
                            //--- Size of the file  in Bytes 
                            saveInfo.Append("&lt;DT>Size of the file  in Bytes ::<DD> " + dnFileBE.Size + " bytes");
                            //--- Mime category of the file type
                            saveInfo.Append("&lt;DT>File Mime Type::<DD> " + dnFileBE.ContentType + "");
                            break;

                        //case dnError:
                        case dnSaveResultsEnum.dnError:
                            //--- The Error
                            LabelTitle.Text = "Files could not be saved by UpFilesBE!!";
                            saveInfo.Append("&lt;DD>" + dnFileBE.Error + "");
                            break;

                        default:
                            //--- The  unknown Error
                            LabelTitle.Text = "Files could not be saved by UpFilesBE!!";
                            saveInfo.Append("An unknown error has occurred. dnSaveResultsEnum: " + dnFileBE.Processed +
                                ". " + dnFileBE.Error);
                            break;
                    }
                }
            }

            LabelSaveInfo.Text = saveInfo.ToString();
        }
        catch (Exception ex)
        {
            ///--- display any errors that may have accured during processing 
            Page.Response.Write("&lt;B>WebServer exception:</B><BR>" +
                ex.Message);
        }
        finally
        {
            ///--- Call Dispose in finally to cleanup
            if (dnUpFilesBE != null)
            {
                dnUpFilesBE.Dispose();
                dnUpFilesBE = null;
            }
        }
    }
    
    
    
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        // if (Session["PROGRESSID"] == null)
        if (Session["PROGRESSID"] == null)
            return;


        // if (Session["PROGRESSID"] is not null
        // Get the ProgID from session object
        ProgID = Session["PROGRESSID"].ToString();

        //call the GetProgress(ProgID) methode which returns string[] collection object;
        //All the values aof the progress are in this  collection object;
        string[] Progressparams = GetProgress(ProgID);

        //Percentage to set the inner table width
        string temp = Progressparams[0];
        if (temp == "0%")
        {
            this.LabelStatus.Text = "Waiting...";

            if (Session["CANCELLED"] != null)
            {
                this.LabelStatus.Text = "Cancelling...";
            }
            
            ButtonCancel.Enabled = false;
            return;
        }

        // Set Status
        this.LabelStatus.Text = "Transfering...";

        // Enable Cancel Button
        ButtonCancel.Enabled = true;

        temp = temp.Substring(0,  temp.Length -1);
        int width = System.Convert.ToInt32(temp);
        TablePercentage.Width = Unit.Percentage(width);

        //write Uploaded Data information to
        //LabelDataUploaded
        this.LabelDataUploaded.Text = temp + "%" + " (" + Progressparams[9] + ")/";
        this.LabelDataUploaded.Text += "(" + Progressparams[8] + ") Uploaded at ";
        this.LabelDataUploaded.Text += Progressparams[2];

        //write CurrentFile to the Table cell
        this.LabelCurrentFile.Text = Progressparams[1];

        //write Elapsed Time to 
        //write LabelTimeElapsed
        this.LabelTimeElapsed.Text = Progressparams[5];

        //write Remaining Time to 
        //write LabelTimeRemaining
        this.LabelTimeRemaining.Text = Progressparams[6];
    }


    public string[] GetProgress(string pID)
    {
        // declare string[] array with ten varaibles
        string[] Progressparams = new string[10];

        //create DNUpFilesProgressBE object
        DNUpFilesProgressBE dNUpFilesProgressBE = new DNUpFilesProgressBE();

        // set ProgressId to pid from the QueryString
        dNUpFilesProgressBE.ProgressId = pID;

        // start Monitor
        dNUpFilesProgressBE.Monitor = true;

        int per = dNUpFilesProgressBE.Percentage;

        //write Percentage to set the inner table width
        string temp = (System.Web.UI.WebControls.Unit.Percentage(per)).ToString();
        Progressparams[0] = temp;

        //write CurrentFile to the Table cell
        temp = dNUpFilesProgressBE.CurrentFile;
        Progressparams[1] = temp;

        //write BytesPerSecondAverage to the Table cell
        temp = (dNUpFilesProgressBE.BytesPerSecondAverage / 1024).ToString() + " KB/sec";
        Progressparams[2] = temp;

        //write Finished status to the Table cell
        temp = dNUpFilesProgressBE.Finished.ToString();
        Progressparams[3] = temp;

        //write Percentage to the Table cell
        temp = dNUpFilesProgressBE.Percentage.ToString() + "%";
        Progressparams[4] = temp;

        //write SecondsElapsed to the Table cell
        temp = dNUpFilesProgressBE.TimeElapsed;
        Progressparams[5] = temp;

        //write SecondsRemaining to the Table cell
        temp = dNUpFilesProgressBE.TimeRemaining;
        Progressparams[6] = temp;

        //write Started status  to the Table cell
        temp = dNUpFilesProgressBE.Started.ToString();
        Progressparams[7] = temp;

        //write TotalBytes to the Table cell
        temp = ((float)dNUpFilesProgressBE.TotalBytes / 1024).ToString() + " KB";
        Progressparams[8] = temp;

        //write TransferredBytes to the Table cell
        temp = ((float)dNUpFilesProgressBE.TransferredBytes / 1024).ToString() + " KB";
        Progressparams[9] = temp;

        return Progressparams;
    }
    
    protected void ButtonCancel_Click(object sender, EventArgs e)
    {
        if (Session["PROGRESSID"] == null)
            return;

        //get ProgID from Session["PROGRESSID"] key object
        ProgID = Session["PROGRESSID"].ToString();


        // call CancelUpload(ProgID);
        CancelUpload(ProgID);

        // set Status to "Canceling...";
        this.LabelStatus.Text = "Canceling...";

        // set Session["CANCELLED"] key to "True";
        Session["CANCELLED"] = "True";
    }


    public int CancelUpload(string pID)
    {
        //create DNUpFilesProgressBE object
        DNUpFilesProgressBE dNUpFilesProgressBE = new DNUpFilesProgressBE();

        // set ProgressId to pid from the QueryString
        dNUpFilesProgressBE.ProgressId = pID;

        // call Cancel operation of the  dNUpFilesProgressBE object
        dNUpFilesProgressBE.Cancel();

        return 0;
    }
}


Conclusion

Conclusion

There are many other samples in the zip file and they use Ajax library released prior to AJAX.NET libraries.

You can download fully functional file upload components packages application from http://www.expandata.net/downloads

 

References

  1. Search Engine
  2. ASP.NET Resources
  3. http://riverasp.net

Download Source Code



Other Related and Popular Articles :

Sending Email in ASP.NET 2.0
Send email in ASP.NET 2.0 Framework with or without SMTP Authentication
URL Rewriting with ASP.NET 2.0
How to implement URL Rewriting and Improve your SEO rankings.
Building a Photo Tagging Application using ASP.NET 2.0, LINQ, and Atlas
In this article, I will examines how to build a photo tagging application using ASP.NET 2.0, LINQ and Atlas framework.
Using LINQ to XML (and how to build a custom RSS Feed Reader with it)
In this article, Scott examines how to work with LINQ using XML. He also demonstrates how to build a custom RSS Feed Reader using these technologies.
Creating Contact Us Form easily using ASP.NET and SMTP
This article explain how to create a simple contact us form by using ASP.NET and System.Net.Mail to send email to the website owner
Build a DotNetNuke FileManager in ASP.NET
Tutorial and Code Sample on building a DotNetNuke FileManager in ASP.NET

Author Profile : Majid Malik

Click here to view Author Profile


How would you rate the quality of this content?
Poor Excellent

Comments

Leave New Comments


Article Content copyright by Majid Malik
Everything else Copyright © by WorldofASP.NET 2008
 
Announcements
Earn Cash by writing an article or review
For more info Click here







Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | Contact Us | SiteMap | Link To Us | Contact Us
© 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | Windows Web Hosting | FREE ASP.NET CMS | Phone Card | PHP Directory | Bangkok Hotels |Calling Card