Use jQuery Uploader to display the File Upload progress

Source: Internet
Author: User

Please Download the sample code in the JQueryElement sample section of the resource Download section (Download the sample code from the script house)
This article describes the functions and precautions of the Uploader control:
* Preparation
* Create and save page
* Add the FileUpload control.
* Set EnableSessionState
* Call the Save method of Uploader.
* Create a page for obtaining progress
* Create an upload page
* Set the Save page
* Set the page for obtaining progress
* Upload
* Hide the Save page


Preparation
Make sure that you have downloaded JQueryElement. dll from the Download resource to Download the latest JQueryElement version.
Use commands to reference the following namespace:
Copy codeThe Code is as follows:
<% @ 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 also need to reference the jQueryUI script and style to Download the JQueryElement of the resource. dll download section download the compressed package contains a custom style jQueryUI, if you need a more simplified style, you can download in the http://jqueryui.com/download: in addition to the namespace, you also need to reference the jQueryUI script:
Copy codeThe Code is as follows:
<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 and save page
The Save page is a simple page, mainly used to save files. The save page is not submitted by itself, but submitted by the upload page.
Add the FileUpload Control
First, add the FileUpload control to the Save page:
Copy codeThe Code is as follows:
<Form id = "formFileUpload" runat = "server">
Upload: <asp: FileUpload ID = "file" runat = "server"/>
</Form>

You can also add an input element whose type attribute is file:
Copy codeThe Code is as follows:
<Form id = "formFileUpload" runat = "server" enctype = "multipart/form-data">
Upload: <input type = "file" id = "file" runat = "server"/>
</Form>

If the input element is used, you may need to set the enctype attribute of form to multipart/form-data.
Set EnableSessionState
You need to set the EnableSessionState of the Save page to ReadOnly, so that you can request the page for obtaining the progress when saving the file on the SAVE page. This is mainly because ASP. NET sequential execution can read and write sessions:
Copy codeThe Code is as follows:
<% @ 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 on the Save page, call the Save static method of the Uploader control to Save the file:
Copy codeThe Code is as follows:
Protected void Page_Load (object sender, EventArgs e)
{
If (this. IsPostBack & this. file. HasFile)
// TODO: The waitSecond parameter is set here to display the upload progress during the test,
// Do not set waitSecond in actual use and adjust 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, the IsPostBack and HasFile attributes are used to determine whether the file is saved after the user submits the file.
The format of the Save method is Save (string filePath, HttpPostedFile postedFile, Uploader. uploadInfo uploadInfo, int bufferSize, int waitSecond), The filePath parameter is the complete path for file storage, and the postedFile parameter is an HttpPostedFile object that provides file control, which can be obtained from the FileUpload control, the uploadInfo parameter is the object that stores the upload progress information. The bufferSize parameter is the cache size when the file is saved. The default value is KB. The last parameter waitSecond is used only during testing, indicates the waiting time after the cache is saved, so that you can see the progress.
To upload a file larger than 4 mb, modify the maxRequestLength of web. config by referring to http://msdn.microsoft.com/zh-cn/library/e1f13641 (v = vs.71). aspx.
Create a page for obtaining progress
The object Uploader. UploadInfo that contains the progress information is saved in the Session, so you can get the progress information from the Session at any time:
Copy codeThe Code is as follows:
<% @ 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)
);
}

Note that uploader_getprec implements the IReadOnlySessionState interface instead of the IRequiresSessionState interface. the reason is similar to setting EnableSessionState to ReadOnly. for how to return JSON data, see in different.. NET returns JSON.
Create upload page
The last step is to create an upload page and add the Uploader control to the page:
Copy codeThe Code is as follows:
<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 ('finished, image path:' +-: 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
You can choose to save the page by using the UploadUrl attribute of Uploader. In this example, the page FileUpload. aspx is selected, which automatically generates an iframe element. The src attribute of iframe points to the FileUpload. aspx page.
You can also customize an iframe and select this iframe through the Upload attribute:
Copy codeThe Code is as follows:
<Iframe id = "myIFrame" src = "FileUpload. aspx"> </iframe>
<Je: Uploader ID = "uploader" runat = "server" IsVariable = "true"
Upload = "# myIFrame"
...>
</Je: Uploader>

Set the page for obtaining progress
You can obtain and display the upload progress through the properties ProgressUrl and ProgressChanged. ProgressUrl indicates the page address of the returned progress information, and ProgressChanged indicates the returned progress and other information.
In addition, the ProgressInterval attribute indicates the time interval of the query progress. The default value is 1000 milliseconds.
Upload
Call the upload method of uploader to trigger the upload operation:
Copy codeThe Code is as follows:
<Je: Button ID = "cmdUpload" runat = "server" IsVariable = "true"
Label = "start" Click ="
Function (){
Uploader. _ uploader ('upload ');
} ">
</Je: Button>

By default, the submit operation is performed on the first form on the SAVE page. You can use the UploadForm attribute to adjust the index of the form to be submitted.
Hide save page
Call the hide method of uploader to hide and save the page:
Copy codeThe Code is as follows:
Uploader. _ uploader ('upload ');

JQueryElementIs open source shared code, you can download dll or source code on the http://code.google.com/p/zsharedcode/wiki/Download page.

Actual process demo: http://www.tudou.com/programs/view/-Zvwz5xsih8/, It is recommended to watch in full screen.

Welcome to panzer open source project, http://zsharedcode.googlecode.com/, which contains IEBrowser control WebBrowser to execute various js and jQuery scripts as well as recording functions and jQueryUI Asp.net controls JQueryElement, Weibo: http://t.qq.com/zoyobar

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.