Tuesday, October 21, 2008

File Upload with AJAX.NET Progress Bar

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

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.


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");
}
}


////
/// ////////////////////////////////////////
///

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();
}


///
/// /////////////////////////////////
///

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 = "<DT>All files have been successfully processed by UpFilesBE!!";
else
LabelTitle.Text = "<DT>No files have been submitted to UpFilesBE!!";

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("<DD> ");
saveInfo.Append("<DT>----------------------------------------");
}

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

if (dnFileBE.Size == 0)
{
LabelTitle.Text = "<DT>Some files could not be processed by UpFilesBE!!";
saveInfo.Append("<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("<DT>File name::
" + dnFileBE.Name + "");
//--- Form File Field Name
saveInfo.Append("<DT>Form File Field name::
" + dnFileBE.FormName + "");
//--- dnSaveResultsEnum, file save status code
saveInfo.Append("<DT>File Save result of type dnSaveResultsEnum::
" + dnFileBE.Processed + "");
//--- Full path of the file as it appears on the client
saveInfo.Append("<DT>Full path of the file as it appears on the client::
" + dnFileBE.ClientPath + "");
//--- Full path of the file as saved in thge destination folder on the server
saveInfo.Append("<DT>Full path of the file as saved in the destination folder on the server::
" + dnFileBE.DestinationPath + "");
//--- Size of the file in Bytes
saveInfo.Append("<DT>Size of the file in Bytes ::
" + dnFileBE.Size + " bytes");
//--- Mime category of the file type
saveInfo.Append("<DT>File Mime Type::
" + dnFileBE.ContentType + "");
break;

//case dnError:
case dnSaveResultsEnum.dnError:
//--- The Error
LabelTitle.Text = "Files could not be saved by UpFilesBE!!";
saveInfo.Append("<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("<B>WebServer exception:

" +
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

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

No comments: