Click here to Skip to main content
15,884,986 members
Articles / Web Development / HTML

Use jQuery Uploader to Display File Upload Progress

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
17 Dec 2011CPOL3 min read 27.5K   16   2
This article explains the function and the use of Uploader

The original post can be found here.

Introduction/Catalog

Due to limited time, synchronization cannot be guaranteed in more than one blog article. At the following address, you can view up-to-date content, hope you understand:

Please download the sample code at the section jQueryElement demo download of Download jQueryElement, the directory is /uploader/Default.aspx.

This article explains the function and the use of Uploader; the catalog is as follows:

Prepare

Be sure that you have got the latest version of jQueryElement at the section JQueryElement.dll. Download JQueryElement.

Use the following statements to reference namespaces:

ASP.NET
<%@ Register Assembly="zoyobar.shared.panzer.JQueryElement"
 Namespace="zoyobar.shared.panzer.ui.jqueryui.plusin"
 TagPrefix="je" %>
<%@ Register Assembly="zoyobar.shared.panzer.JQueryElement"
 Namespace="zoyobar.shared.panzer.web.jqueryui"
 TagPrefix="je" %>

In addition to the namespace, you need to reference the jQueryUI scripts and styles. There is a custom theme for jQueryUI in the compressed file downloaded at the section JQueryElement.dll of Download jQueryElement. If you need more themes, you can get them at jqueryui.com/download:

HTML
<link type="text/css" rel="stylesheet"
 href="[style path]/jquery-ui-<version>.custom.css" />
<script type="text/javascript"
 src="[script path]/jquery-<version>.min.js"></script>
<script type="text/javascript"
 src="[script path]/jquery-ui-<version>.custom.min.js"></script>

Create Save Page

Save page is a simple page to save files; the save page does not submit itself, but is submitted by the upload page.

Add FileUpload Control

First, add a FileUpload control to the save page:

XML
<form id="formFileUpload" runat="server">
Photo: <asp:FileUpload ID="file" runat="server" />
</form>

You can also add an input element whose attribute type is file:

XML
<form id="formFileUpload" runat="server" enctype="multipart/form-data">
Photo: <input type="file" id="file" runat="server" />
</form>

If you use the input element, you may need to set the enctype attribute of the form to multipart/form-data.

Set EnableSessionState

The save page needs to set EnableSessionState to ReadOnly, so you can request the page that gets the progress when you save the file. This is mainly because ASP.NET orders pages that you can read and write to Session:

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true"
 CodeFile="FileUpload.aspx.cs" Inherits="uploader_FileUpload"
 EnableSessionState="ReadOnly" %>

Call the Save Method of Uploader

In the Page_Load method of the save page, call the static method Save of the Uploader control to save the file:

C#
protected void Page_Load ( object sender, EventArgs e )
{

 if ( this.IsPostBack && this.file.HasFile )
  // TODO: Parameter waitSecond is set in order to show upload progress in test,
  // do not set waitSecond if you want to use this page,
  // and adjust the bufferSize to a reasonable value.
  Uploader.Save (
   this.Server.MapPath ( @"~/uploader/photo.jpg" ),
   this.file.PostedFile,
   this.Session["myphotouploadinfo"] as Uploader.UploadInfo,
   1,
   1 );
  // Uploader.Save (
  //  this.Server.MapPath ( @"~/uploader/photo.jpg" ),
  //  this.file.PostedFile,
  //  this.Session["myphotouploadinfo"] as Uploader.UploadInfo );

}

In the code, use the properties IsPostBack and HasFile to determine whether the user has submitted files.

The format of the method Save is Save ( string filePath, HttpPostedFile postedFile, Uploader.UploadInfo uploadInfo, int bufferSize, int waitSecond ). The parameter filePath is the full path of the saved file, postedFile is an HttpPostedFile object which can be obtained from the FileUpload control, uploadInfo is an object that contains the upload progress information, bufferSize is the cache size when you save the file, default is 128 KB, and waitSecond is used only during testing, which represents the wait time after the cache is saved, so you can ensure to see progress.

Create Page that Gets the Progress

The object Uploader.UploadInfo that contains the progress information is saved in the Session, so you can get progress information from the Session at any time:

C#
<%@ WebHandler Language="C#" Class="uploader_getprec" %>

using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using zoyobar.shared.panzer.ui.jqueryui.plusin;

public class uploader_getprec : IHttpHandler,
 IReadOnlySessionState
{
 public void ProcessRequest ( HttpContext context )
 {
  context.Response.ContentType = "text/javascript";
  context.Response.Cache.SetNoStore ( );

  Uploader.UploadInfo info =
   context.Session["myphotouploadinfo"] as Uploader.UploadInfo;

  SortedDictionary<string, object> json =
   new SortedDictionary<string, object> ( );

  if ( null == info )
   json.Add ( "prec", "-" );
  else
  {
   json.Add ( "prec", info.Percent );
   json.Add ( "total", info.ContentLength );
   json.Add ( "posted", info.PostedLength );

   if ( info.Percent == 100 )
    json.Add ( "url", "photo.jpg" );

   /*
    * {
    * "prec": 20.23
    * "total": 2000,
    * "posted": 2
    * }
    * */
  }

  context.Response.Write (
   new JavaScriptSerializer ( ).Serialize ( json )
   );
 }

 ...

}

It is important to note, uploader_getprec implements the interface IReadOnlySessionState, rather than the IRequiresSessionState. The reason is similar to setting EnableSessionState to ReadOnly. As for how to return the JSON, please refer to Return JSON in Different .NET Versions.

Create Upload Page

The final step is to create the upload page, add the Uploader control in the page:

JavaScript
<je:Uploader ID="uploader" runat="server" IsVariable="true"
 UploadUrl="FileUpload.aspx"
 ProgressUrl="getprec.ashx" ProgressChanged="
function(data){

 if(-:data.prec == '-')
  $('#prec').text('no progress!');
 else
  if(-:data.prec == 100){
   $('#prec').text('ok, the url is: ' + -:data.url);

   pb.hide();

   $('#photo').show().attr('src', -:data.url);
  }
  else{
   $('#prec').text(-:data.posted +
    ' bytes/' + -:data.total + ' bytes, ' +
    -:data.prec + '%');
   pb.progressbar('option', 'value', -:data.prec);
  }
}
">
</je:Uploader>
<je:Button ID="cmdUpload" runat="server" IsVariable="true"
 Label="Start" Click="
function(){
 cmdUpload.hide();
 uploader.__uploader('hide').__uploader('upload');

 pb.show();
}">
</je:Button>

Set Save Page

By using the UploadUrl property of Uploader, you can choose the save page. In the example, we select FileUpload.aspx as the save page, which will automatically generate an iFrame element whose src attribute is FileUpload.aspx.

You can also customize an iframe, and then select this iFrame through the Upload property:

XML
<iframe id="myIFrame" src="FileUpload.aspx"></iframe>

<je:Uploader ID="uploader" runat="server" IsVariable="true"
 Upload="#myIFrame"
 ... >
</je:Uploader>

Set Progress Page

Via the properties ProgressUrl and ProgressChanged, we can obtain and display the upload progress. ProgressUrl is the URL of the progress page, ProgressChanged will handle the progress information.

In addition, the ProgressInterval property represents the query interval of the progress page, the default is 1000 milliseconds.

Upload

Call the upload method of uploader to trigger the upload operation:

JavaScript
<je:Button ID="cmdUpload" runat="server" IsVariable="true"
 Label="Start" Click="
function(){
 uploader.__uploader('upload');
}">
</je:Button>

By default, the first form of the save page will be submitted; the index of form which will be submitted can be adjusted by the property UploadForm.

Hide Save Page

Call the hide method of uploader, you can hide the save page:

JavaScript
...
 uploader.__uploader('hide');
...

Related Content

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questiongetprec.ashx Pin
Clingfree30-Dec-11 7:27
Clingfree30-Dec-11 7:27 
AnswerRe: getprec.ashx Pin
zoyobar30-Dec-11 21:59
zoyobar30-Dec-11 21:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.