Use swfupload to upload files

Source: Internet
Author: User
What is swfupload?

Swfupload is a website front-end File Upload Component. With Flash + JavaScript, swfupload enables multiple files to be uploaded in batches (in fact one by one) without refreshing the webpage and displays the upload progress.

Basic Principles of swfupload

1. Traditional HTML form File Upload

Traditional file uploads use the following form:

1 <form
id="file-form"
action="http://www.gearcode.com/upload.php"
enctype="multipart/form-data"
method="post">
2     <input
name="filename"
type="file"
/>
3     <input
type="submit"
value="Upload"
/>
4 </form>

For such a form, only one file can be selected for each input file. If you want to upload multiple files, you need to use js to dynamically Add "<input type =" file "name =" FILENAME "/>" to the form ". You need to click the "Browse" button for each input file to open the file selection window and select files one by one. Instead of opening a window where you can select multiple files, you can use ctrl or shift to select one or more files at a time.

In addition, when you select a file and Click Upload, the form will be submitted. It is unknown about the progress and speed of file upload.

2. Upload after swfupload is used

Swfupload inserts a flash button into the webpage, allowing users to click to pop up the file selection dialog box. In other words, the dialog box of the selected file is popped up in swfupload.swf. Of course, you need to click this flash. Therefore, swfupload needs to set the button style displayed during initialization, such as width, height, background color, Font, padding, and image ....... In addition to these styles, you also need to set the button display position and other configurations. These common configurations will be detailed later in this article.

Because the swfupload Select File Dialog Box is popped up by flash, you can select multiple files in this dialog box. After selecting a file, swfupload.swf calls back some JavaScript Functions and transmits some basic information of the selected file as parameters to these callback functions so that developers can set these callback functions, HTML to display the file information to the page.

After selecting the files to be uploaded, these files will be added to the swfupload upload queue. Once the "startupload ()" function of the swfupload instance is called, swfupload will upload the file to the specified address through flash. This upload address can also be set when swfupload is instantiated, and this address is the action of receiving the file, for example, action = "upload. PHP ". Note that after startupload is called, swfupload only submits the first unuploaded file in the Upload File queue, instead of all the files in the Upload File queue, if you call startupload again after a file is uploaded, swfupload starts to upload the next unuploaded file in the queue. Therefore, to achieve automatic batch upload, you only need to call startupload In the callback function after the upload is completed.

During the upload process, swfupload has many events, such as the start of the upload, the upload progress changes, the upload error, the upload is successful, and the upload is complete ...... We can set the callback functions for these events. swfupload will call our callback functions when these events occur, and send the corresponding information to our callback function in the form of parameters. In this way, you can dynamically display the file upload status and progress by handling these events.

Preparations before start

1. Obtain swfupload

The official address of swfupload is http://www.swfupload.org/. the download of swfuploadis on Google Code: http://code.google.com/p/swfupload/downloads/list.
V2.2.0.1.

2. Online Documentation

Http://demo.swfupload.org/Documentation/

3. demos of swfupload 2.2

Http://demo.swfupload.org/v220/index.htm

Use swfupload to upload files

1. initialize swfupload

First, extract the downloaded "swfupload v2.2.0.1 core.zip" to a swfupload.jsfolder and a swfupload.swf (in the Flash directory), and copy the two files to your project. The compressed package also contains some other files, such as English documents, changelog, and license, which are not discussed in this article. You do not need to import them to your project during actual application.

Introduce swfupload. js on the page where swfupload is used to upload components:

1 <script
type="text/javascript"
src="http://www.gearcode.com/lib/swfupload/swfupload.js"
type="text/javascript"></script>

. There is a function named "swfupload". We create this function instance to initialize swfupload and input some Initialization Configuration information. Specifically, it is necessary to go to the newswfuploadafter the web page is complete, because swfupload.swf is determined by replacing an HTML element on the page. Therefore, if swfupload is instantiated before the HTML element is created, a javascript error will occur.

Instantiate swfupload and set initialization parameters:

01 var swfu;
02 // Jquery is used here. After the body onload, that is, after the webpage is loaded, swfupload is instantiated.
03 $(function(){
04     swfu =
new SWFUpload(config == undefined ? {
05         upload_url : path+"/fileUpload.action",
06         flash_url : path+"/plugin/uploader/SWFUpload/swfupload.swf",
07         file_size_limit :
"20 KB",
08         file_types :
"*.jpg;*.jpeg;*.png;*.bmp;*.gif",
09         file_types_description :
"All Image Files",
10         file_post_name :
"fileQueue",
11  
12         button_placeholder_id :
"spanSWFUploadButton",
13         button_width : 60,
14         button_height : 20,
15         button_text :
"<B> Add a file </B>",
16         button_text_left_padding : 3,
17         button_text_top_padding : 2,
18         button_cursor : SWFUpload.CURSOR.HAND,
19  
20         //handler
21         file_queued_handler : Handler.fileQueued,
22         file_queue_error_handler : Handler.fileQueueError,
23         upload_complete_handler : Handler.uploadComplete,
24         upload_start_handler : Handler.uploadStart,
25         upload_progress_handler : Handler.uploadProgress,
26         upload_success_handler : Handler.uploadSuccess
27     });
28 });

You can use the above code to create a swfupload instance "swfu". All subsequent operations on the file queue must be completed by calling the method of this instance.

. Other features starting with "{button_}" are used to set the display style of swfupload.swf. Most of the initialization parameters are very simple. I will not repeat them here. You can refer to the online swfupload document mentioned above. Note that after swfupload is initialized, the corresponding HTML node on the page is replaced with the flash button we set. However, if your page is not opened using the HTTP protocol, clicking this button does not bring up the select file dialog box.

For example, I open the page directly in the folder on the desktop:

File: // C:/Documents and Settings/jasonlee/desktop/upload/upload.html

Open the page in this way. clicking the flash button will not pop up the select file dialog box. Therefore, during the test, you need to deploy the page upload to the server and open it as an http protocol. For example:

Http://www.gearcode.com/demo/file-upload/upload.html

2. Start upload

After initialization, click the flash upload button to open the select file dialog box. After the file is selected, the dialog box is closed. The selected file enters the upload queue. To start uploading, you only need to call the startupload function of swfupload. For example:

1 swfu.startUpload();

However, if there are multiple files in the queue, only the first unuploaded file will be uploaded after startupload () is called. As mentioned above, the bulk upload of swfupload is to automatically upload files one by one. To enable automatic batch upload, you only need to call the start upload method again after the file is uploaded successfully. We can implement this by setting the handler function of swfupload:

1 upload_complete_handler: function(file) {
2     this.startUpload();
3 }

3. Handler Function

Swfupload generates many events during work. These events are of great use to us (for example, to display the file size, upload progress, speed, and other information on the page). We can set the handler function to monitor these events, when swfupload triggers these events, it will actively call the callback function we set and pass the file information as a parameter to our callback function.

Swfupload has many handler functions. Here we only introduce the following six commonly used Event Callback functions:

Event name Initialization parameter name Parameters Event triggering
Filequeued File_queued_handler File Triggered when each file enters the upload queue
Filequeueerror File_queue_error_handler File, errorcode, message When each file enters the upload queue, an error is triggered.
Uploadstart Upload_start_handler File Triggered when each file starts to be uploaded.
Uploadprogress Upload_progress_handler File, bytesloaded, bytestotal Triggered when the upload progress of each file changes
Uploadsuccess Upload_success_handler File, serverdata Triggered after each file is uploaded successfully
Uploadcomplete Upload_complete_handler File Triggered after each file is uploaded

For example, to listen to the uploadprogress event, you need to set the value of the upload_progress_handler parameter during swfupload initialization:

1 swfu = new
SWFUpload({
2     // Omit other initialization parameters...
3     upload_progress_handler: uploadProgress
4 });

Then create a callback function for the listener event:

1 function uploadProgress(file, bytesLoaded, bytesTotal) {
2     //...
3 }

In this way, the uploadprogress function is called every time the upload progress changes during file upload, in addition, the file information, the number of uploaded bytes, and the total number of bytes of the file are sent to the callback function.

The usage of other callback functions is the same, so we will not describe them here. Finally, we will introduce the callback function parameter file. Almost all callback functions use file as a parameter. file is a JavaScript Object with the following structure (from the official online documentation ):

{
ID: string,
Index: Number,
Name: string,
Size: Number,
Type: string,
Creationdate: date,
Modificationdate: date,
Filestatus: Number,
}

The following is a brief description of each attribute in the file object:

Attribute name Type Description
ID String Swfupload is the ID generated by the file in the queue
Index Number Object index value. You can use GetFile (INDEX) to obtain the object.
Name String Original file name, excluding the original file directory
Size Number File size, in bytes
Type String File Type
Creationdate Date File Creation Time
Modificationdate Date Last file modification time
Filestatus Number File status in the upload queue. You can use swfupload. file_status to compare the File status.
Conclusion

So far, we have mastered the basic usage of swfupload. Because the author's technology is not refined and the knowledge of ActionScript is basically zero, he will not analyze swfupload code in depth. While writing an article, I made a demo. The code is ugly and only for cainiao to download:

SWFUpload-demo.zip

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.