For the SWFUpload usage guide, please refer to:https://www.example.com/w3cnote/swfupload-guide.html

Table of Contents

  1. SWFUpload
  2. SWFUpload Version 2
  3. Overview)
  4. Getting Started)
  5. SWFUpload JavaScript Object)
    1. Constructor
    2. Globals and Constants)
      1. New: instances
      2. movieCount
      3. New: QUEUE_ERROR
      4. New: UPLOAD_ERROR
      5. New: FILE_STATUS
      6. New: UPLOAD_TYPE
      7. New: BUTTON_ACTION
      8. New: CURSOR
      9. New: BUTTON_WINDOW_MODE
      10. New: RESIZE_ENCODING
      11. New: onload
    3. Properties
      1. New: customSettings
      2. movieName
    4. Methods
      1. addSettingDeprecated
      2. getSettingDeprecated
      3. retrieveSettingRemoved (in v2.1.0)
      4. destroyAdded in v2.1.0
      5. displayDebugInfo
      6. selectFile
      7. selectFiles
      8. startUpload
      9. New: startResizedUpload (added in v2.5.0)
      10. cancelUpload
      11. stopUpload
      12. New: requeueUpload
      13. getStats
      14. setStats
      15. getFile
      16. New: getQueueFile (added in v2.5.0)
      17. addPostParam
      18. removePostParam
      19. addFileParam
      20. removeFileParam
      21. setUploadURL
      22. setPostParams
      23. setFileTypes
      24. setFileSizeLimit
      25. setFileUploadLimit
      26. setFileQueueLimit
      27. setFilePostName
      28. setUseQueryString
      29. setDebugEnabled
      30. setButtonImageURL (added in v2.2.0)
      31. setButtonDimensions (added in v2.2.0)
      32. setButtonText (added in v2.2.0)
      33. setButtonTextStyle (added in v2.2.0)
      34. setButtonTextPadding (added in v2.2.0)
      35. setButtonDisabled (added in v2.2.0)
      36. setButtonAction (added in v2.2.0)
      37. setButtonCursor (added in v2.2.0)
    5. New: Events
      1. flashReady
      2. New: swfUploadPreload
      3. New: swfUploadLoadFailed
      4. New: swfUploadLoaded
      5. New:buttonAction
      6. fileDialogStart
      7. fileQueued
      8. New: fileQueueError
      9. fileDialogComplete
      10. New:uploadResizeStart
      11. uploadStart
      12. uploadProgress
      13. uploadError
      14. New:uploadSuccess
      15. uploadComplete
      16. debug
    6. SWFUpload Utility Objects
      1. Settings Object
      2. Settings Description
      3. New: Support Object
      4. File Object
      5. Stats Object
  6. SWFUpload Plug-ins
  7. New: Known Issues

SWFUpload

SWFUploadOriginallyVinterwebb.seA client-side file upload tool developed. It combines JavaScript and Flash to provide a capability (and good user experience) in the browser that is superior to the traditional upload tag <input type="file" />.

SWFUpload's main features:

  • Multiple files can be selected in the file browsing dialog.
  • AJAX-style uploads without page refresh.
  • Various events during the upload process.
  • Can resize images on the client side.
  • The class namespace it uses is compatible with various JS libraries (i.e., jQuery, Prototype, etc.).
  • Supports Flash 9 and Flash 10 (support for Flash 8 was dropped after version 2.2.0).

SWFUpload's design philosophy differs from other Flash-based upload tools. SWFUpload gives developers as much UI control as possible. Developers can use XHTML, CSS, and JavaScript to make it better fit their website's style. It provides a set of simple JS events to update upload status, and developers can use these events to display file upload progress on the webpage.

Unfortunately, Flash Player 10 forces us to use a button (after clicking) to trigger the file selection dialog, but SWFUpload allows developers to use JS to modify the button's text and appearance.

SWFUpload v2

SWFUpload v2 includes many new features, enhanced stability, fixes some bugs in Flash Player, and provides some useful plug-ins. New features include:

  • Can leverage Flash Player 10 security features.
  • Can POST additional data with uploads.
  • Sends POST data for each file upload.
  • Complete set of events.
  • All settings and parameters can be flexibly configured.
  • Can retrieve data returned from the server.
  • Can pause files being uploaded instead of canceling.
  • Can change the upload order arbitrarily.
  • Can provide a single-file or multi-file selection dialog.
  • Can limit upload queue length, file size, and number of uploaded files.
  • Can handle 0-byte files better.
  • Each file has an upload confirmation event.

Overview

HTML Upload

The standard HTML upload box only provides a button and a text box for users to select a single file. It is then submitted via a form. The entire file must wait until upload completes before the file size and extension can be confirmed and checked, and there is little feedback during the upload process. This causes some inconvenience.

But traditional HTML upload is very simple, a single step, and supported by all browsers.

SWFUpload

SWFUpload uses a Flash movie to select and upload files. The movie has a customizable button to activate the file selection dialog. The file selection dialog allows users to select a single file or multiple files. The types of files that can be selected can also be restricted; developers can limit users to selecting only specified appropriate files, e.g., *.jgp;*.gif.

Once files are selected and OK is clicked, each file is validated and placed in the queue. When Flash uploads the files, predefined JavaScript events are triggered to update the UI display on the page, and also provide upload status and error information in real time.

File uploads are independent of the page and form. Each file is uploaded separately to the processing page, which makes it simple and easy for the server to handle the files. The upload service provided by Flash means the entire page does not need to be submitted or refreshed. This is a bit like an AJAX application. The Form data on the page is processed separately from the file upload controlled by Flash.

Getting Started

SWFUpload is not a drag-and-drop upload control. Therefore, some DOM and JS knowledge is required. Several demos will show SWFUpload's capabilities and how to use them to accomplish tasks.

SWFUpload consists of 4 parts:

  1. Initialization and Settings (JavaScript)
  2. JavaScript library: SWFUpload.js
  3. Flash control: swfupload.swf and swfupload_fp9.swf
  4. Event handling mechanism (JavaScript)

Many problems with using SWFUpload come from the setup. Incorrect event handling, Flash/browser bugs, or server configuration.

Initialization and Settings

SWFUpload must be initialized on the page. It is usually done in the window.onload event of JS. The SWFUpload constructor needs to get an object of type Object (JS). The data of this object is passed directly to the constructor.

The reference of the initialized SWFUpload object should be saved well (yukon: i.e., store it in a variable, like 'swfu' in the example), because this reference is also needed when starting file uploads and controlling other features.

Example:When initializing SWFUpload, pass an anonymous object directly to configure parameters.

var swfu; window.onload = function () { swfu = new SWFUpload({ upload_url : "http://www.swfupload.org/upload.php", //处理上传文件的地址 flash_url : "http://www.swfupload.org/swfupload.swf", //核心功能swf的地址 flash9_url : "http://www.swfupload.org/swfupload_fp9.swf", file_size_limit : "20 MB" //文件大小限制 }); };

Example:You can also use an object variable (settings_object) to pass configuration parameters when initializing SWFUpload.

var swfu; window.onload = function () { var settings_object = { upload_url : "http://www.swfupload.org/upload.php", flash_url : "http://www.swfupload.org/swfupload.swf", flash9_url : "http://www.swfupload.org/swfupload_fp9.swf", file_size_limit : "20 MB" }; swfu = new SWFUpload(settings_object); };

JavaScript library

To use SWFUpload, the JS library file (swfupload.js) must be included in the page using it.

Once the SWFUpload object is created, many functions can be accessed. Developers can use this to control SWFUpload.

Example:How to include the swfupload.js library

<script type="text/javascript" src="../www.swfupload.org/swfupload.js"></script>

Example:Initialize SWFUpload on demand.

var swfu = new SWFUpload({ upload_url : "http://www.swfupload.org/upload.php", flash_url : "http://www.swfupload.org/swfupload.swf", flash9_url : "http://www.swfupload.org/swfupload_fp9.swf", button_placeholder_id : "spanSWFUploadButton" //yukon:这里有个新参数,将会使用js在id为"spanSWFUploadButton"的标签容器如span,div中创建一个"选择"按钮 });

[New Content] Flash Control

The SWFUpload JavaScript library can dynamically load the Flash control (swfupload.swf or swfupload_fp9.swf).

The file address of the Flash control must be defined in the SWFUpload settings object at initialization.

The Flash control is actually a small Flash movie that can control file selection, validation, and upload.

What it presents to the user on the page is a button with a customizable UI, and it can detect the Flash Player version (9, 10) and automatically load the Flash control suitable for the user's player version.

Use flash_url and flash9_url to set the paths of swfupload.swf or swfupload_fp9.swf. (yukon: The previous examples have already mentioned this.)

Event Handlers

Developers must create a set of JavaScript functions to handle SWFUpload events. These functions are triggered when various important events occur.

By handling SWFUpload events, developers can provide feedback on upload progress, error messages, and upload completion. Note: Developers should not override functions stored in SWFUpload.prototype.

Example:SWFUpload event handling and initialization.

// uploadStart event handler function. The value of the "upload_start_handler" property in the settings object should be the name of this function. var myCustomUploadStartEventHandler = function (file) { var continue_with_upload; if (file.name === "the sky is blue") { continue_with_upload = true; } else { continue_with_upload = false; } return continue_with_upload; }; // uploadSuccess event handler function. The value of the "upload_success_handler" property in the settings object should be the name of this function. var myCustomUploadSuccessEventHandler = function (file, server_data, receivedResponse) { alert("The file " + file.name + " has been delivered to the server. The server responded with " + server_data); }; // Create the SWFUpload Object var swfu = new SWFUpload({ upload_url : "http://www.swfupload.org/upload.php", flash_url : "http://www.swfupload.org/swfupload.swf", flash9_url : "http://www.swfupload.org/swfupload_fp9.swf", file_size_limit : "200 MB", upload_start_handler : myCustomUploadStartEventHandler, upload_success_handler : myCustomUploadSuccessEventHandler

SWFUpload JavaScript Object

Constructor

SWFUpload(settings object) //SWFUpload(settings object)

Returns:An SWFUpload instance

var swfupload_instance = new SWFUpload(settings_object);

Globals and Constants

SWFUpload defines some global variables and constants that are useful for advanced SWFUpload applications and error handling. They are all read-only.

[New Content] SWFUpload.instances

SWFUpload.instances is an array object that stores references to all SWFUpload instances on a page. Flash Player relies on this array of objects to call the correct event handler functions. The index of the SWFUpload.instances object array (SWFUpload.instances[index]) is the movieName property.

SWFUpload.movieCount

SWFUpload.movieCount is a global variable that records how many SWFUpload object instances have been created on the page and ensures that each Flash movie is given a unique movieName.

[New Content] SWFUpload.QUEUE_ERROR

SWFUpload.QUEUE_ERROR is a simple JavaScript object containing constants for queue error codes. It is used to determine what error code is sent when a file queue error (fileQueueError) occurs.

SWFUpload.QUEUE_ERROR = { QUEUE_LIMIT_EXCEEDED : -100, FILE_EXCEEDS_SIZE_LIMIT : -110, ZERO_BYTE_FILE : -120, INVALID_FILETYPE : -130 };
  • QUEUE_LIMIT_EXCEEDED - Indicates that the user has queued too many files, exceeding the maximum queue length. However, once files in the queue are uploaded or removed, the user can still add files to the upload queue.
  • FILE_EXCEEDS_SIZE_LIMIT - Indicates that the file exceeds the set file size limit (file_size_limit).
  • ZERO_BYTE_FILE - Indicates that the selected file is 0 bytes. Flash Player cannot handle empty files. Uploading Windows shortcut icons can also trigger this error.
  • INVALID_FILETYPE - Indicates that the selected file's extension does not match the allowed types. This error can be triggered when the user manually enters a filename with an incorrect extension rather than selecting a file by clicking with the mouse.

[New Content] SWFUpload.UPLOAD_ERROR

SWFUpload.UPLOAD_ERROR is also a simple JavaScript object containing upload error code constants. It is used to determine what error code is sent when an upload error (uploadError) event occurs.

SWFUpload.UPLOAD_ERROR = { HTTP_ERROR : -200, MISSING_UPLOAD_URL : -210, IO_ERROR : -220, SECURITY_ERROR : -230, UPLOAD_LIMIT_EXCEEDED : -240, UPLOAD_FAILED : -250, SPECIFIED_FILE_ID_NOT_FOUND : -260, FILE_VALIDATION_FAILED : -270, FILE_CANCELLED : -280, UPLOAD_STOPPED : -290 };
  • HTTP_ERROR - An upload to the server was attempted, but the server did not return a 200 status code (200 indicates no errors).
  • MISSING_UPLOAD_URL - The upload URL (upload_url) is not set.
  • IO_ERROR - Some error occurred while reading and sending the file. This usually happens when the server unexpectedly closes the connection.
  • SECURITY_ERROR - A security error; the upload violated security constraints. This is rare.
  • UPLOAD_LIMIT_EXCEEDED - The user attempted to upload more files than the preset limit.
  • UPLOAD_FAILED - An error occurred while attempting to initialize the upload. This is rare.
  • SPECIFIED_FILE_ID_NOT_FOUND - A file started uploading, but the file could not be found. (yukon: After the file was selected and added to the queue, the user renamed or deleted the file on disk, etc.)
  • FILE_VALIDATION_FAILED - An error was returned when the upload started.
  • FILE_CANCELLED - The upload was cancelled (the cancelUpload function was called).
  • UPLOAD_STOPPED - The upload was paused (the stopUpload function was called).
  • RESIZE_ERROR - An error occurred while resizing the image.

[New Content] SWFUpload.FILE_STATUS

SWFUpload.FILE_STATUS is a JavaScript object containing file status code constants. It is used to check the file status property of the File object.

SWFUpload.FILE_STATUS = { QUEUED : -1, IN_PROGRESS : -2, ERROR : -3, SUCCESS : -4, CANCELLED : -5 };
  • QUEUED - Indicates that the file is waiting in the upload queue.
  • IN_PROGRESS - Indicates that the file is currently being uploaded.
  • ERROR - Indicates that the file caused a queue or upload error.
  • COMPLETE - Indicates that the file has been successfully transmitted to the server.
  • CANCELLED - Indicates that the upload of this file was cancelled (the cancelUpload function was called).

[New Content] SWFUpload.UPLOAD_TYPE [Purpose: Determines the upload type]

SWFUpload.UPLOAD_TYPE is a JavaScript object containing upload type constants. It is used to check the upload type property of the File object.

  • NORMAL - A normal SWFUpload upload.
  • RESIZED - A resized image upload, with data sent via HTTP POST.

[New Content] SWFUpload.BUTTON_ACTION [Purpose: Determines the action to perform when the button is clicked]

SWFUpload.BUTTON_ACTION is a JavaScript object containing button action code constants. It is used to set the value of button_action, thereby configuring the interactive button in the Flash movie's responses to various mouse actions.

SWFUpload.BUTTON_ACTION = { SELECT_FILE : -100, SELECT_FILES : -110, START_UPLOAD : -120 }

  • SELECT_FILE - When the button is clicked, a single-file selection dialog opens. The (JavaScript-defined) mouse click event is not triggered.
  • SELECT_FILES - When the button is clicked, a multi-file selection dialog opens. The (JavaScript-defined) mouse click event is not triggered.
  • START_UPLOAD - When the button is clicked, the first file in the upload queue will be uploaded. The (JavaScript-defined) mouse click event is not triggered.
  • NONE - In this case, the (JavaScript-defined) mouse click event is triggered.
  • JAVASCRIPT - Same as NONE. This value is deprecated.

[New Content] SWFUpload.CURSOR [Purpose: Changes the mouse cursor style]

SWFUpload.CURSOR is a JavaScript object containing button cursor constants. It is used to set the value of button_cursor, thereby changing the mouse cursor style when the pointer is over the button.

SWFUpload.CURSOR = { ARROW : -1, HAND : -2 }
  • ARROW - The cursor appears as an arrow pointer.
  • HAND - The cursor appears as a hand.

[New Content] SWFUpload.WINDOW_MODE [Purpose: The display mode of the movie]

SWFUpload.WINDOW_MODE is a JS array object that contains button movie wmode parameter constants. It is used to tell the browser how to render the Flash movie.

Some WINDOW_MODE/WMODE settings can cause browser issues; see below for details.Known Issues.

SWFUpload.WINDOW_MODE = { WINDOW : "window", TRANSPARENT : "transparent", OPAQUE : "opaque" };
  • WINDOW is the default mode. The Flash movie is drawn on the topmost layer of the page.
  • OPAQUE allows other page elements to cover this button movie.
  • TRANSPARENT. The button background is transparent, allowing HTML elements to be displayed underneath it.

[New] SWFUpload.RESIZE_ENCODING [Purpose: indicates the image encoding format]

SWFUpload.RESIZE_ENCODING is a JS array object that contains resize encoding type constants. It is used to indicate the encoding format of the resized image.

  • JPEG - JPEG encoding format
  • PNG - PNG encoding format

[New] SWFUpload.onload [Purpose: defines the operation function after the page has loaded]

onload is a function that can be executed via the swfobject's addDOMLoadEvent method. You can use this method to execute your script after the page has loaded. However, you should make sure you are not using other similar methods (such as jQuery's "Ready" or Prototype's dom:loaded).

SWFUpload.onload = function () { new SWFUpload(settingsObject); }

The example above will initialize SWFUpload at the earliest browser load event. Most DOM ready events execute immediately after the window.onload event.

Properties

Please follow the property list descriptions below when using these properties. If a read-only or write-only property is used incorrectly, it will cause SWFUpload errors.

[New content] customSettings (read/write) [Purpose: developer custom settings]

The customSettings property is an empty JS object. It is used to store data related to a SWFUpload instance. Its contents can be initialized using the custom_settings property in the settings object.

Example:

// 初始化 SWFUpload 对象时使用一些自定义设置 var swfu = new SWFUpload({ custom_settings : { custom_setting_1 : "custom_setting_value_1", custom_setting_2 : "custom_setting_value_2", custom_setting_n : "custom_setting_value_n", } }); swfu.customSettings.custom_setting_1 = "custom_setting_value_1"; // 改变一个已有的自定义设置 swfu.customSettings.myNewCustomSetting = "new custom setting value"; // 添加一个新的自定义设置 // 用一个全新的对象来重写自定义设置 swfu.customSettings = { custom_setting_A : "custom_setting_value_A", custom_setting_B : "custom_setting_value_B" };

Values stored in the customSettings object can be easily accessed by event handlers: (yukon: this property uses the dynamic features of JS to give developers a high degree of freedom)

function uploadSuccess(file, serverData, receivedResponse) { if (this.customSettings.custom_setting_A === true) { alert("Checked the custom setting!"); } }

movieName (read-only) [Purpose: stores a unique identifier for a SWFUpload instance]

Contains the unique identifier name for a SWFUpload instance. This value can be passed to Flash to help with AS-JS interaction. It is used to index the instance in the SWFUpload.instances array. You should not and cannot change it.

Methods

The following methods are used to operate SWFUpload. Some methods can be bound to click events of DOM elements, and others are used internally by SWFUpload when handling events.

object addSetting(setting_name, value, default_value)

Deprecated The addSetting function sets a setting value. If the value is undefined then the default_value is used. The function is used by SWFUpload

addSetting returns the value that was stored in the setting.

object getSetting(setting_name)

Deprecated The getSetting function retrieves the value of a setting. If the setting is not found an empty string is returned.

object retrieveSetting(setting_value, default_value)

Removed in v2.1.0. The retrieveSetting function is similar to the addSetting function except it does not modify the internal settings object. retrieveSetting returns the setting_value unless it is undefined, in which case it returns the default_value.bool destroy() [Purpose: destroys a SWFUpload instance]

This is a utility function.

Added in v2.1.0

Removes a SWF DOM element and destroys the internal references of SWFUpload. It is used to completely remove a SWFUpload instance from the page, preventing memory leak issues in IE.

Returns true if successfully removed; returns false if any error occurs leaving the SWFUpload instance in an inconsistent state.

void displayDebugInfo() [Purpose: outputs debug information]

In debug events, displayDebugInfo() outputs the SWFUpload settings. If the debug setting is set to true during initialization, this function is called automatically.

Not recommended. Incompatible with Flash Player 10.

void selectFile()

Not recommended. Incompatible with Flash Player 10.

selectFile causes the Flash Control to display a File Selection Dialog window. A single file may be selected from the Dialog window.

Calling selectFile begins the File Event Chain.

void selectFiles()

Not recommended. Incompatible with Flash Player 10.

selectFiles causes the Flash Control to display a File Selection Dialog window. A multiple files may be selected from the Dialog window.

Calling selectFiles begins the File Event Chain.

void startUpload(file_id) [Purpose: starts uploading files]

startUpload accepts the file_id parameter to upload a file. If no file_id value is passed to it, the first file in the upload queue will be uploaded by default.

Calling startUpload triggers the Upload Event Chain.

[New] void startResizedUpload(file_id, width, height, encoding, quality, allowEnlarging) [Purpose: upload with image resizing]

startResizedUpload accepts the file_id parameter to upload a file. SWFUpload attempts to adjust the file width/height and other settings (if the image format is supported by Flash). If the image format is not supported, an uploadError is triggered.

The width and height parameters are used to set the maximum width and height of the image. However, the aspect ratio is maintained during resizing.

The encoding value must be a constant in SWFUpload.RESIZE_ENCODING.

quality can only be used to adjust the quality of JPEG format images. It accepts a range of 0-100. If it is outside this range, it is forced to 0 or 100.

The allowEnlarging parameter defines whether SWFUpload allows the original image to be enlarged (default is true) when the original image's width/height are smaller than the specified width and height. If set to false, the image will still be encoded, but it will not be enlarged.

Calling the startResizedUpload method triggers the normal upload event chain. However, Flash Player does not provide uploadProgress events periodically. SWFUpload only sends simulated 0% and 100% uploadProgress events.

The resized image is submitted via POST (rather than as FILE) because Flash Player 10 introduced security features.The PHP processing page for upload with image resizing differs from the normal upload PHP processing page:

$resizedImageData = $_POST["Filedata"]; // 服务器端以$_POST方式接收数据而不是 $_FILE $fileHandle = fopen("image.jpg", "w"); //以file系列操作函数来存储图片 fwrite($fileHandle, $resizedImageData); fclose($fileHandle);

void cancelUpload(file_id, trigger_error_event) [Purpose: removes an upload]

cancelUpload accepts the file_id parameter to remove a file upload. This file will be removed from the upload queue.

If no file_id is given, the first file in the upload queue will be canceled by default.

If the optional parameter trigger_error_event is set to false, the uploadError event will not be triggered.

void stopUpload() [Purpose: stops file upload]

stopUpload stops the currently uploading file and restores it to the upload queue. (yukon: unlike removal, it cancels the upload of this file but does not remove it from the upload queue)

When stopUpload is called, if there is a file uploading, the uploadError event will be triggered; if there is no file uploading at the moment, no action will occur and no event will be triggered.

[New] bool requeueUpload(file_id or index) [Purpose: re-queue]

requeueUpload adds a previously queued file back to the waiting upload queue.

Returns false if the file is not found, or if it is currently being uploaded.

Note: A re-queued file will not be checked again against file size, queue size, total upload count, or other restrictions; it is only added to the queue, if the file reference still exists.

object getStats() [Purpose: returns the current stats object]

Returns the stats object.

void setStats(stats_object) [Purpose: sets or modifies the stats object]

Sets or modifies the Stats Object. If you want to change the upload success count or upload failure count after upload is complete, you can use this method.

object getFile(file_id|index) [Purpose: gets a specific file object from the queue]

getFile returns the file object in the queue by accepting a file id (the id of a file object) or a file index (the index attribute of a file object).

When a file_id is passed to getFile, only files in the queue can be retrieved; if no file is found, null is returned.

When an index is passed to getFile, all files that have attempted to be queued (including files that caused errors during queuing) can be retrieved. If the index is out of range, null is returned.

[New] object getQueueFile(file_id|index) [Purpose: Returns a specific file object in the upload queue]

getQueueFile is used to return a single file object from the upload queue. Specifically, it returns the file object in the queue by accepting a file id (the id of a file object) or a file index (the index attribute of a file object). The index starts from 0.

When a file_id is passed to getQueueFile, only files in the waiting upload queue can be retrieved; if no file is found, null is returned.

When an index is passed to getQueueFile, only files in the waiting upload queue can be retrieved. For example: getQueueFile(0) returns a file object at the head of the waiting upload queue. If the startUpload function is called, it will be uploaded after the current upload finishes.

(yukon: The difference between the above two methods may be: getFile retrieves files from the file queue, including uploaded, errored, and waiting upload queues. getQueueFile only retrieves files from the waiting upload queue.)

void addPostParam(name, value) [Purpose: Adds a key/value pair]

addPostParam adds a key/value pair that is sent along via POST when each file is uploaded.

It corresponds to the same key/value pair in the post_params setting. If the value already exists in post_params, it will actually be overwritten.

void removePostParam(name) [Purpose: Removes a key/value pair]

removePostParam removes a key/value pair that was previously sent along via POST when each file was uploaded.

It corresponds to the same key/value pair in the post_params setting. If the value already exists in post_params, it will actually be removed.

bool addFileParam(file_idspan>, name, value)

Adds a POST key/value pair to a specific file object with the specified file_id. If the added name attribute already exists, the original value will be overwritten.

If you need to add POST values to all file objects, you can use the post_params property in the settings.

bool removeFileParam(file_id, name)

Deletes the POST value pair added by addFileParam.

Returns false if this property does not exist in the POST settings.

void setUploadURL(url)

Dynamically modifies the upload_url property in the settings.

void setPostParams(param_object)

Dynamically modifies post_params, all previous properties are overwritten. param_object must be a basic JavaScript object, and all properties and values must be string types.

void setFileTypes(types, description)

Dynamically modifies file_types and file_types_description in the settings; both parameters are required.

void setFileSizeLimit(file_size_limit)

Dynamically modifies file_size_limit in the settings; this modification is valid for subsequent file size filtering. The file_size_limit parameter accepts a unit; valid units are B, KB, MB, GB, and the default unit is KB.

For example: 2147483648 B, 2097152, 2097152KB, 2048 MB, 2 GB

void setFileUploadLimit(file_upload_limit)

Dynamically modifies file_upload_limit in the settings; the special value 0 means unlimited.

Note:This limits the total number of files successfully uploaded under the control of one SWFUpload instance.

void setFileQueueLimit(file_queue_limit)

Dynamically modifies file_queue_limit in the settings; the special value 0 means unlimited.

Note:This limits the total number of files allowed to be queued in the file upload queue (files that pass the queue detection are added to the upload queue to wait for upload).

void setFilePostName(file_post_name)

Dynamically modifies file_post_name in the settings. Note that FlashPlayer ignores this setting in the Linux environment.

void setUseQueryString(use_query_string)

Dynamically modifies use_query_string in the settings. When set to true, SWFUpload sends data via GET; if false, it sends data via POST.

void setDebugEnabled(debug_enabled)

Dynamically enables/disables debug output; the debug_enabled parameter is a boolean value.

void setButtonImageURL(url)

Dynamically modifies the button image. The url parameter is an image relative to the swf file or an absolute address (for example: a relative path starting with / or an absolute path: http://www.swfupload.org/buttonImage.png). All image types supported by FLASH can be used (gif, jpg, png).

The button image needs to be processed according to certain rules (CSS Sprite). The button image must include the 4 states of the button, from top to bottom: normal, hover, down/click, disabled. (Refer to the image in the official demo.)

void setButtonDimensions(width, height)

Dynamically modifies the size of the SWF movie to fit the button image size. The value must be a pure number and cannot include length units. The height must be 1/4 of the entire button image height to ensure correct display.

void setButtonText(text)

Dynamically sets the text displayed in the Flash Button, supporting HTML. The style of HTML text can be set via CSS selectors together with the setButtonTextStyle method. If the text is too large, the overflowing part will be hidden. For details on Flash text's HTML support, see...Adobe's Flash documentation。

void setButtonTextStyle(css_style_text)

Together with the setButtonText method, CSS styles can be used to dynamically set the text style in the Flash Button. For details on Flash text's CSS support, see...Adobe's Flash documentation

void setButtonTextPadding(left, top)

Sets the left and right padding of the Flash button text. The value can be negative.

void setButtonDisabled(isDisabled)

When set to 'true', the Flash button is disabled, and any button actions and operations will be ignored.

void setButtonAction(buttonAction)

Defines the action to execute after the mouse is clicked. The BUTTON_ACTION constant enumeration stores the available values for this method.

void setButtonCursor(buttonCursor)

Sets the style of the mouse pointer when pointing at the button. The CURSOR constant enumeration stores the available values for this method.

[New content] Events

SWFUpload triggers a series of events during operation. Developers can use these callback handling events to control the UI, control operations, or report errors.

All events are called in the context of the SWFUpload instance, so using this in these callback events can directly access the instance object that triggered the event.

All events should be preset in the setting parameter during instance initialization.

[New:]

When uploading a file, events are called in the following order (upload event chain):

  • Upload start with additional image resizing function uploadResizeStart
  • Normal upload start uploadStart
  • Uploading in progress uploadProgress (called repeatedly during the file upload process)
  • Upload error uploadError (called when certain errors occur; the upload will be cancelled or stopped)
  • Upload success uploadSuccess (the file was successfully uploaded and the server received usable data)
  • Upload complete uploadComplete (upload finished, SWFUpload is ready to start uploading the next one)

flashReady()

This event function is an internal event and therefore cannot be overridden. When the loaded Flash control completes all initialization operations, this event is triggered to notify SWFUpload that it can accept various commands.

Note:Corresponds to the custom event swfupload_loaded_handler in the settings.

[New] swfUploadPreload()

The swfUploadPreload event is triggered after SWFUpload has confirmed available features but before the Flash Movie is fully loaded. If the handler of this event returns false, swfupload will stop loading. It is typically used to handle cases where the browser does not support an important feature parameter.

This event handler can be set in the swfupload_preload_handler property of the settings object.

[New] swfUploadLoadFailed()

When the page cannot load the Flash movie normally. Usually because Flash Player is not installed or its version is lower than 9.0.28.

This event handler can be set in the swfupload_load_failed_handler property of the settings object.

[New] swfUploadLoaded()

The swfUploadLoaded event is triggered after Flash is loaded and ready. It is configurable. The swfUploadLoaded event notifies you that Flash is loaded and all methods can be safely executed.

This event handler can be set in the swfupload_loaded_handler property of the settings object.

[New] mouseClick()

The mouseClick event is triggered only when the button is clicked (and the value of button_action setting is SWFUpload.BUTTON_ACTION.NONE, or the flash button is set to disabled). If the value of button_action settings is other, or the flash button is enabled, this event will not be triggered.

This event handler function can be set in the mouse_click_handler property of the settings object.

[New] mouseOver()

The mouseOver event will be triggered when the mouse moves over any part of the Flash movie.

This event handler function can be set in the mouse_over_handler property of the settings object.

[New] mouseOut()

The mouseOut event is triggered when the mouse leaves the Flash movie.

This event handler function can be set in the mouse_out_handler property of the settings object.

fileDialogStart()

This event is triggered after selectFile or selectFiles is called, and before the file selection dialog is displayed. Only one file dialog can exist at a time.However, this event handler function will not be executed until the file selection dialog is closed.

This event handler function can be set in the file_dialog_start_handler property of the settings object.

fileQueued(file object)

When the files are selected and the file selection dialog closes and disappears, if the selected files are successfully added to the upload queue, this event will be triggered once for each successfully added file (N files successfully added to the queue, the event triggers N times).

Corresponds to the custom event file_queued_handler in settings.

[New content]fileQueueError(file object, error code, message)

 

When the file selection dialog closes, if the selected files fail to be added to the upload queue, this event will be triggered once for each file that encountered an error (this event and the fileQueued event are triggered exclusively; there are only two possibilities when adding a file to the queue: success or failure).

Possible reasons for file queue errors: 1. Exceeds the upload size limit, 2. File is zero bytes, 3. Exceeds the file queue quantity limit, 4. Invalid file type outside the allowed types.

(yukon: after testing, the content of message is as follows:

1. Exceeds the upload size limit: message=File size exceeds allowed limit.

2. File is zero bytes: message=File is zero bytes and cannot be uploaded.

3. Exceeds the file queue quantity limit: message=int (refers to the queue size limit you set).

4. Invalid file type outside the allowed types: message=File is not an allowed file type.

If you want to change these messages, please modify them in swfupload.as in the open source package, then recompile into swfupload.swf.

)

The specific error cause can be obtained from the error code parameter. The type of error code can be seen in the definitions in SWFUpload.QUEUE_ERROR.

Reminder:Corresponds to the custom event file_queue_error_handler in settings.

Note:If the number of selected files to queue exceeds the quantity limit in the settings, then no files will be queued, and this event is triggered only once. If the quantity limit is not exceeded, each file will be checked for file type and size; for files that fail the check, this event is triggered, while files that pass are successfully queued.

fileDialogComplete(number of files selected, number of files queued, total number of files in the queued)

When the file selection dialog closes and all selected files have been processed (whether successfully added to the upload queue or failed), this event is triggered. number of files selected is the number of selected files, number of files queued is the number of files from this selection that were successfully added to the queue.

Reminder:Corresponds to the custom event file_dialog_complete_handler in settings.

Note:If you want files to upload automatically after selection, calling this.startUpload() in this event is a good choice. If stricter determination is needed, you can check the number of queued files before calling upload; if it is greater than 0, you can start uploading.

[New] uploadResizeStart(file object, width, height, encoding, quality)

The uploadResizeStart event handler function is called when an image starts to be resized. No progress events or handling methods are provided during the resizing process. However, re-encoding the image may take some time. If an error occurs during this period, the uploadError event will be triggered.

When resizing is complete, SWFUpload continues to trigger the uploadStart event and begins the same event chain as a normal upload.

uploadStart(file object)

The uploadStart event is triggered before the file starts uploading to the server. This event handler function can perform final validation before upload and other operations you need, such as adding, modifying, or deleting post data.

After completing the final operations, if the function returns false, the upload will not be started; if it returns true or returns nothing, the upload will officially start.

Reminder:Corresponds to the custom event upload_start_handler in settings.

uploadProgress(file object, bytes complete, total bytes)

The uploadProgress event is periodically triggered by the Flash control.It provides three parameters to access the uploaded file object, the uploaded bytes, and the total bytes respectively. Therefore, you can periodically update UI elements on the page in this event to display upload progress in a timely manner.

Note:Under Linux, Flash Player triggers this event only once after the entire file has been uploaded. Officially, this is a bug in the Linux Flash Player, and the current SWFUpload library cannot solve it.。

Reminder:Corresponds to the custom event upload_progress_handler in settings.

uploadError(file object, error code, message)

Whenever the upload is terminated or does not complete successfully, thenuploadErrorthe event will be triggered. The error code parameter indicates the current error type. For more specific error types, seeSWFUpload.UPLOAD_ERRORthe definitions in. The Message parameter represents the error description. The File parameter represents the file object that failed to upload.

For example, if we request a non-existent file processing page on the server, then error code will be -200 and message will be 404. Stopping, quitting, uploadStart returning false, HTTP errors, IO errors, exceeding the file upload number limit, etc., will all trigger this event. Upload error will not fire for files that are cancelled but still waiting in the queue.(I still have doubts about this official statement. After a file is cancelled, how can it remain in the upload queue?)

Reminder:Corresponds to the custom event upload_error_handler in settings.

Note:At this point, the file upload cycle has not yet ended, so you cannot start uploading the next file here.

[New content] uploadSuccess(file object, server data, received response)

When the file upload processing is complete (here "complete" only means that the Files information has been sent to the target handler; it only cares about sending, not whether it was successfully received), and the server returns an HTTP status of 200, theuploadSuccessevent is triggered.server dataRefers to some data sent by the server (for example, what you echo out), whilereceived responseis the HTTP status code sent by the server itself.

Due to some Flash Player bugs, the HTTP status code may not be obtained, causing the uploadSuccess event not to be triggered. For this reason, version 2.50 added a new property assume_success_timeout in the settings object to set whether the maximum time waiting for the HTTP status code has been exceeded; if exceeded, uploadSuccess is triggered. In this case,(received response)the parameter will be invalid.

The http_success in the settings object allows setting the uploadSuccess event to also be triggered when the HTTP status code is a non-200 value. In this case no server data is available from the Flash Player.

In

Reminder:Corresponds to the custom event upload_success_handler in settings.

Note:
  1. server data is the data returned by the server-side handler.
  2. At this point, the file upload cycle has not yet ended, so you cannot start uploading the next file here.
  3. On the Windows platform, the server-side handler must return a non-empty value after processing the file storage; otherwise, this event will not be triggered, and the subsequent uploadComplete event cannot be executed.

uploadComplete(file object)

When a file in the upload queue completes an upload cycle, whether successful (uoloadSuccess triggered) or failed (uploadError triggered), the uploadComplete event will be triggered. This also marks the completion of one file's upload, and the next file can be uploaded.

If you want the next file to upload automatically, calling this.startUpload() at this point to start uploading the next file is a good choice. However, use it with caution. See the notes.

Reminder:Corresponds to the custom event upload_complete_handler in the settings.

Note:When uploading multiple files, if you use cancelUpload midway to cancel the file being uploaded, or use stopUpload to stop the file being uploaded, then you must be very careful when using this.startUpload() in uploadComplete, because in the above cases uploadError and uploadComplete will execute sequentially. Therefore, although the upload of the current file is stopped, the next file will be uploaded immediately. You may find this strange, but in fact the program is not wrong. If you wish to terminate the automatic upload of the entire queue, you will need to do additional program handling.

debug(message)

If the debug setting is set to true, a textArea will be automatically added at the bottom of the page. If this debug event has not been overridden, both the SWFUpload library and Flash will call this event to add debug information to the output box at the bottom of the page for debugging purposes.

Reminder:Corresponds to the custom event debug_handler in the settings.

Utility Objects SWFUpload Utility Objects

Settings object Settings object

It is a JavaScript Object type variable that provides configuration for the initialization of a SWFUpload instance.Each configuration property in it can only appear once.Many properties are optional. If an optional property is not configured, the appropriate default value specified in the SWFUpload library will be used. For details, see the detailed introduction to settings.

For example:(All properties that can be configured in settings)

Example:

{ upload_url : "http://www.swfupload.org/upload.php", flash_url : "http://www.swfupload.org/swfupload.swf", flash9_url : "http://www.swfupload.org/swfupload_fp9.swf", file_post_name : "Filedata", post_params : { "post_param_name_1" : "post_param_value_1", "post_param_name_2" : "post_param_value_2", "post_param_name_n" : "post_param_value_n" }, use_query_string : false, requeue_on_error : false, http_success : [201, 202], assume_success_timeout : 0, file_types : "*.jpg;*.gif", file_types_description: "Web Image Files", file_size_limit : "1024", file_upload_limit : 10, file_queue_limit : 2, debug : false, prevent_swf_caching : false, preserve_relative_urls : false, button_placeholder_id : "element_id", button_image_url : "http://www.swfupload.org/button_sprite.png", button_width : 61, button_height : 22, button_text : "<b>Click</b> <span class="redText">here</span>", button_text_style : ".redText { color: #FF0000; }", button_text_left_padding : 3, button_text_top_padding : 2, button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES, button_disabled : false, button_cursor : SWFUpload.CURSOR.HAND, button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT, swfupload_loaded_handler : swfupload_loaded_function, mouse_click_handler : mouse_click_function, mouse_over_handler : mouse_over_function, mouse_out_handler : mouse_out_function, file_dialog_start_handler : file_dialog_start_function, file_queued_handler : file_queued_function, file_queue_error_handler : file_queue_error_function, file_dialog_complete_handler : file_dialog_complete_function, upload_start_handler : upload_start_function, upload_progress_handler : upload_progress_function, upload_error_handler : upload_error_function, upload_success_handler : upload_success_function, upload_complete_handler : upload_complete_function, debug_handler : debug_function, custom_settings : { custom_setting_1 : "custom_setting_value_1", custom_setting_2 : "custom_setting_value_2", custom_setting_n : "custom_setting_value_n", } }

Detailed Description of Settings Parameters Settings Description

New upload_url

Default value:Empty string

The upload_url setting accepts an absolute or relative complete URL relative to the SWF file. It is recommended to use a complete absolute path to avoid request path errors caused by browsers and FlashPlayer modifying the base path setting. (yukon: This is actually relative. If your swfupload and the PHP upload file processing page are always placed in the same website folder, I would recommend using a relative path)

If the preserve_relative_urls property of the settings object is false, SWFUpload will convert relative paths to absolute paths to avoid URLs being parsed into various different formats by Flash Player on different systems. If you disable this conversion of SWFUpload, you should use a relative path to set the location of swfupload.swf.

Note:The FlashPlayer security domain model needs to be considered here.

file_post_name

Default value:Filedata

The file_post_name parameter allows you to set the name value of the uploaded file in the POST information (similar to setting the name attribute of <input type="file" name="Filedata"/> in a traditional form).

Note: (Pending in version 2.5)This parameter setting is invalid on Linux; the received name is always Filedata. Therefore, to ensure maximum compatibility, it is recommended to use the default value for this parameter.

New post_params

Default value:Empty object

post_params defines a set of key/value pairs that are sent along to the server when uploading each file. This property can be assigned with a JavaScript array object. Key/value pairs must be plain strings or numbers. (Can be checked with JavaScript's typeof() function)

Note: Flash Player 8 does not support sending post data along. SWFUpload will automatically send post_params in the form of a query string.

use_query_string

Default value:false

This property can be set to true or false, and determines whether post_params are sent via GET. If false, they are sent via POST. Introduced in v2.1.0.

New preserve_relative_urls

Default value:false

preserve_relative_urls accepts a boolean variable. It indicates whether SWFUpload converts relative URLs to absolute URLs. If set to true, they will not be converted. The default is false, i.e., automatic conversion.

requeue_on_error

Default value:false

This property can be set to true or false. If set to true, when an uploadError occurs on a file object (except for fileQueue errors and FILE_CANCELLED errors), the file object will be reinserted at the front of the upload queue instead of being discarded. If needed, the requeued file can be uploaded again. If you want to remove the file object from the upload queue, you must use the cancelUpload method.

All events associated with an upload failure will also be triggered one by one. Therefore, requeuing an upload-failed file may conflict with the Queue Plugin (or custom code that automatically uploads the entire file queue). If the code calls the startUpload method to automatically upload the next file and no measures are taken to remove the upload-failed file from the upload queue, then the requeued upload-failed file will start uploading again, fail again, be requeued, upload again... entering an endless loop.

This setting was introduced in v2.1.0.

http_success

Default value:[]

This array allows customizing the HTTP status values that trigger the success event. Status 200 always triggers success, and only status 200 provides serverData.

When accepting an HTTP status value other than 200, the server does not need to return content.

New assume_success_timeout

Default value: 0

assume_success_timeout sets how many seconds SWFUpload will wait to detect a server response; on timeout, it will force the upload success (uploadSuccess) event to be triggered. This property is intended to work properly around a Flash Player bug, avoiding long waits for server responses, and also solving the bug where Flash Player on Mac OS cannot make the server return content.

Flash will ignore the server response 30 seconds after the last uploadProgress event is triggered and force the upload success event.

If assume_success_timeout is set to 0, this feature will be disabled. SWFUpload will wait for a long time for Flash Player to trigger the uploadSuccess event.

file_types

Default value:*.*

Sets the file type filtering rules for the file selection dialog. This property accepts semicolon-separated file type extensions, for example "*.jpg;*.gif", which only allows users to see and select jpg and gif files in the file selection dialog. By default, all file types are accepted.

Reminder:This setting is only a filter for the client browser and has no restrictions on file type filtering in server-side file processing. If you need strict file filtering, the server side also needs program detection.

file_types_description

Default value:All Files

Sets the file description displayed to the user in the file selection dialog.

file_size_limit

Default value:0

Sets the file size filtering rules for the file selection dialog. This property accepts a numeric value with a unit; available units are B, KB, MB, GB. If the unit is omitted, KB is used by default. The special value 0 means no file size limit.

Reminder:This setting is only effective for the client browser and has no restrictions on server-side file processing. If you need strict file filtering, the server side also needs program handling.

file_upload_limit

Default value:0

Sets the maximum number of files that a SWFUpload instance is allowed to upload, and is also the upper limit of the file_queue_limit property in the settings object. Once the user has successfully uploaded files or added files to the queue reaching the maximum number, no more files can be added. The special value 0 means there is no limit on the number of uploads. Only files that are uploaded successfully (the upload triggered the uploadSuccess event) count toward the upload limit. The setStats method can be used to modify the number of successfully uploaded files.

Note:This value cannot be used across pages; it is also reset when the page is refreshed. Strict file upload count limits should be detected and managed by the server.

file_queue_limit

Default value:0

Set the maximum limit for files waiting in the file upload queue. When a file is successfully uploaded, encounters an error, or is removed from the upload queue, if the number of files in the queue has not yet reached the limit, new files can be added to the queue to replace that file's position. If the maximum number of files allowed to upload (file_upload_limit) or the remaining number of allowed uploads is less than the file queue limit (file_queue_limit), the smaller value will be used.

flash_url

Default value:Empty string

Set an absolute or relative full URL relative to this upload page. Once the SWFUpload instance is instantiated, this setting cannot be modified.

Note:Testing found that the setUploadURL method can be used to modify this setting.

[New] flash9_url

(Added in v2.5.0)Flash control (SWF) supporting Flash Player 9. Absolute or relative URL.

flash_width

(Removed in v2.1.0) Defines the width of the HTML element that contains the flash. Some browsers do not function correctly if this setting is less than 1 px. This setting is optional and has a default value of 1px.

flash_height

(Removed in v2.1.0) Defines the height of the HTML element that contains the flash. Some browsers do not function correctly if this setting is less than 1 px. This setting is optional and has a default value of 1px.

flash_color

(Removed in v2.2.0) This setting sets the background color of the HTML element that contains the flash. The default value is '#FFFFFF'.

Note: This setting may not be effective in "skinning" 1px flash element in all browsers.

prevent_swf_caching

Default value:true

(Added in v2.2.0)This boolean value sets whether to append a random value to the Flash URL to prevent the browser from caching the SWF movie. This is to solve a bug that appears in some IE-engine-based browsers.

Note:SWFUpload directly appends a random parameter called swfuploadrnd after flash_url. If the given flash_url already contains GET parameters, two question marks will appear as concatenators, causing an error.

debug

Default value:false

This value is a boolean type, setting whether the debug event is triggered.

Note:SWFUpload code compares this variable with the string "true" using strict equality, so it only considers true as debug mode enabled. If set to 1, although JS considers it enabled, and a Debug Console will be generated after initialization, Flash will not output debug information in subsequent operations. (Because I am used to using 1 and 0 for boolean variables, I was once puzzled why Flash debug information could not be output.)

button_placeholder_id

Default value:null

(Added in v2.2.0)This required parameter specifies the ID of the DOM element on the page that swfupload.swf will replace. When the corresponding DOM element is replaced by the SWF element, a style selector named "swfupload" will be added to the SWF container for CSS customization.

button_image_url

Default value:Empty string

(Added in v2.2.0)The biggest change in V2.2.0 is the introduction of a button into the SWF. Using this parameter, you can set an image (or SWF) relative to the swf file or an absolute address as the button UI. All image types supported by Flash can be used (gif, jpg, png, or an SWF).

The button image needs to be processed according to certain rules (CSS Sprite). The button image should include the button's 4 states, from top to bottom: normal, hover, down/click, disabled. (See the image in the official demo.)

button_width

Default value:1

(Added in v2.2.0)Set the width attribute of the SWF.

button_height

Default value:1

(Added in v2.2.0)Set the height attribute of the SWF (1/4 of the button image height)

button_text

Default value:Empty string

(Added in v2.2.0)This property sets the text displayed in the Flash Button, supporting HTML. The style of HTML text can be set through CSS selectors together with the button_text_style parameter. For details on Flash text support for HTML, seeAdobe's Flash documentation。

button_text_style

Default value:"color: #000000; font-size: 16pt;"

(Added in v2.2.0)This parameter works with the button_text parameter to set the text style in the Flash Button via CSS styles. For details on Flash text support for CSS, seeAdobe's Flash documentation

button_text_top_padding

Default value:0

(Added in v2.2.0)Set the distance of the text on the Flash Button from the top. Negative values can be used.

button_text_left_padding

Default value:0

(Added in v2.2.0)Set the distance of the text on the Flash Button from the left. Negative values can be used.

button_action

Default value:SWFUpload.BUTTON_ACTION.SELECT_FILES (multi-file upload)

(Added in v2.2.0)Set the action after clicking the Flash Button. The default is SWFUpload.BUTTON_ACTION.SELECT_FILES; clicking the button will open the multi-file upload dialog. If set to SWFUpload.BUTTON_ACTION.SELECT_FILE, it is single-file upload. If set to SWFUpload.BUTTON_ACTION.START_UPLOAD, it starts file upload.

button_disabled

Default value:false

(Added in v2.2.0)This boolean value sets whether the Flash Button is in a disabled state. When disabled, clicking will not perform any operation.

button_cursor

Default value:SWFUpload.CURSOR.ARROW (arrow cursor)

(Added in v2.2.0)This parameter sets the cursor state when the mouse hovers over the Flash Button. The default is SWFUpload.CURSOR.ARROW; if set to SWFUpload.CURSOR.HAND, it is a hand cursor.

button_window_mode

Default value:SWFUpload.WINDOW_MODE.WINDOW

(Added in v2.2.0)This parameter sets the specific mode in which the browser displays the SWF movie.

custom_settings

Default value:Empty Object

This property accepts data of type Object and can be used to safely store custom information associated with the SWFUpload instance, such as properties and methods, without worrying about conflicts with SWFUpload's internal methods and properties, or compatibility with version upgrades.

After setting, it can be accessed through the customSettings property of the instance.

var swfu = new SWFUpload({ custom_settings : { "My Setting" : "This is my setting", myothersetting : "This is my other setting", integer_setting : 100, a_dom_setting : document.getElementById("some_element_id") } }); var my_setting = swfu.customSettings["My Setting"]); swfu.customSettings["My Setting"] = "This is my new setting"; swfu.customSetting.myothersetting = "another new value"; swfu.customSetting.integer_setting += 25; swfu.customSetting["a_dom_setting"].style.visibility = "hidden";
Event Handlers

Default value:null

The remaining settings define a series of event-handling callback functions. During the operation of SWFUpload,corresponding eventswill be triggered. If you need to perform custom operations in these callbacks, you should define the corresponding JavaScript functions in the settings.

[New] Support Object

The support property of the SWFUpload instance (its type is an object) can confirm whether certain features of SWFUpload are supported by the version of Flash Player used by the browser.

{ load : bool, // 标示SWFupload是否能在当前版本的 Flash Player中载入 imageResize : bool, // 标示当前时候安装了Flash Player 10或更新版本的Flash Player,并且SWFUpload 是否支持客户端调节上传图片的大小。 }

File Object

The File object contains a set of available file properties. Many processing events pass a File Object parameter to access the relevant properties of the file.

{ id : string, // SWFUpload控制的文件的id,通过指定该id可启动此文件的上传、退出上传等 index : number, // 文件在选定文件队列(包括出错、退出、排队的文件)中的索引,getFile可使用此索引 name : string, // 文件名,不包括文件的路径。 size : number, // 文件字节数 type : string, // 客户端操作系统设置的文件类型 creationdate : Date, // 文件的创建时间 modificationdate : Date, // 文件的最后修改时间 filestatus : number // 文件的当前状态,对应的状态代码可查看SWFUpload.FILE_STATUS }

Stats Object

This object provides status information of the upload queue. You can obtain this object by accessing the instance's getStats method.

This object includes the following properties:

{ in_progress : number // 值为1或0,1表示当前有文件正在上传,0表示当前没有文件正在上传 files_queued : number // 当前上传队列中存在的文件数量 successful_uploads : number // 已经上传成功(uploadSuccess触发)的文件数量 upload_errors : number // 已经上传失败的文件数量 (不包括退出上传的文件) upload_cancelled : number // 退出上传的文件数量 queue_errors : number // 入队失败(fileQueueError触发)的文件数量

The values of all these properties can be modified using the setStats method, exceptin_progressandfiles_queued。

SWFUpload Plug-ins

Several plug-ins were introduced after SWFUpload v2.0. They help SWFUpload implement some functions.

Documentation for most plug-ins is in the js plugin folder.

SWFObject

The SWFObject plug-in usesSWFObject libraryto insert the SWFUpload Flash component into the page.

This plug-in also provides a document structure load completion detection feature (Document Ready loading). (yukon: this feature might be like jQuery's $(document).ready()) and flash version detection. Detailed usage is documented in this plug-in folder. You'd better not mix SWFObject's document ready loading detection with similar functions of other libraries. Use only one of them.

Flash Player 10: Because Flash Player 10 requires a button to trigger related operations of the movie, if this button (its id can be indicated by the button_placeholder_id property in the settings object) is set to hidden or display:none by CSS or similar, SWFUpload will fail to load.

Cookies

To fix the Flash Cookie bug, the Cookies plug-in will automatically obtain your browser's cookies and send them with the upload. The cookies will be sent with the upload URL in the form of POST or GET.

This plug-in sends cookie key/value pairs via POST or GET. On the server side, they will not be parsed as cookies. Some frameworks that automatically detect cookies to confirm session and authentication may not be able to obtain the values passed by this plug-in.

Queue Handling

Queue Handling plugin provides queue processing functionality. For example, uploading the entire queue, canceling the entire queue, and automatically starting upload after enqueueing.

Speed

The speed plugin extends several properties of the 'file' object to describe the current upload status. This plugin includes values such as current speed, average speed, elapsed time, and remaining time.

Known Issues

Bugs in Flash Player and many browsers have plagued SWFUpload. But we have been working hard.

Cancelling in Linux

With Flash 9 Player and earlier versions, performing a cancel upload operation on Linux may cause the browser to crash. However, newer versions of Flash Player have improved this issue.

Upload Progress in Linux

Flash Player on Linux only emits an upload progress event (uploadProgress) after the upload is complete, rather than continuously during the upload as it does in Windows.

This is because some Linux distributions lock the entire browser during the upload.

Upload Progress in OS X

We have received some reports that Flash Player on MAC OS does not trigger the uploadProgress event. The specific circumstances are still unknown, but please be aware of the potential issue.

MIME Type

Regardless of the actual MIME type of the file, Flash Player uses mime formatapplication/octet-streamto upload all files.

Maximum number of selected files

Flash Player itself does not limit the maximum number of files that can be selected for upload, but it does limit the maximum total length of file names. This string is composed as: "file name" space "file name" ... The number of files that can be uploaded depends on the operating system's limit on the total length of file names. If the user selects too many files, a warning message from Flash Player will be displayed in the file selection dialog (yukon: I once uploaded 173 files at once on XP without a warning...).

Proxies

Flash Player may not work correctly with proxies. It has some issues when handling proxy authentication, which may cause certain conflicts.

Some antivirus software uses a local client proxy to receive uploaded files and scan them (it seems to intercept the uploaded file, write it to a proxy server, and only after scanning is complete does it actually send it to the target server). This causes SWFUpload to mistakenly believe that the entire file has been uploaded; it will emit a large number of uploadProgress events until 100% is reached. While the proxy is actually uploading to the target server, SWFUpload appears to be paused.

Kaspersky antivirus: Kaspersky(and some other antivirus software) implement a client-side proxy to intercept locally outgoing upload data. SWFUpload cannot detect the existence of this proxy system. These proxy servers can receive uploaded files very quickly, scan them, and then send them to the target server.

Apache security module Apache mod_security

Apache's security module mod_security validates POST messages received by the server. Flash Player implements an edge case (should 'an edge case' be translated as '取巧way of'?) (there is a parameter that can decide whether to validate). POST uploads files, and the server also implements this.

Secure Sockets Layer SSL

We have received reports that Flash Player cannot upload over SSL. The specific circumstances of this problem have not yet been confirmed, but it does seem that uploading under SSL is unreliable. Problems especially occur when using public key self-signed certificates.

Similarly, SSL certificates issued by untrusted Certificate Authorities (CA) cannot be accepted by Flash, because Flash does not provide a method to accept such certificates. As with the previously mentioned cookie bug, Flash Player on Windows only accepts certificates issued by CAs on its trusted list, regardless of the certificate currently in use by the browser.

Authentication

HTTP authentication mechanisms are not well supported by Flash Player. Newer versions of Flash Player are somewhat better; older versions may cause browser crashes.

Prematurely terminated connections

Prematurely ending the response (such as the Response.end() method in ASP.NET) can cause SWFUpload to report an upload failure even though the upload had actually completed.

File POST name: Filedata POST name in Linux

Changing the file receiving name (default "Filedata", set via the file_post_name property in the settings object) does not work in Flash Player on Linux.

Cookie bug

On Windows, in non-IE browsers (FireFox, Opera, Safari, etc.), the Flash plugin sends IE cookies. This breaks session and authentication mechanisms on many servers.

Developers must manually solve the problem of passing Session and authentication cookie information, and also manually modify the session on the server if they want to use sessions.

However, the SWFUpload package provides example code to solve this bug in PHP or ASP.Net.

ExternalInterface bugs

When interacting with the browser/JS, Flash Player cannot correctly use the escape method to encode data. SWFUpload has made great efforts to solve this problem. In the future, if this bug is fixed, SWFUpload will send additional escape-encoded data.

Server Data length bugs

Excessively long server response data can cause errors under Flash Player on MAC or Linux systems. Data may be truncated, altered, or in some cases duplicated. We recommend that the server sends back data that is as short and concise as possible.

Avant Browser

Once cached, SWFUpload does not work correctly on the Avant browser.

Since SWFUpload v2.2.0, the prevent_swf_caching setting has been added to attempt to solve this problem.

File Dialog & Page Changing

Leaving or refreshing the page while the file selection dialog is open will cause the browser to crash. (On all browsers, all operating systems.)

This situation mostly occurs when you set a hyperlink <a>'s "onclick" to call selectFile/selectFiles, but do not prevent its default navigation action. Clicking the link will navigate to another page while also opening the file selection dialog.

(yukon: Another possibility: the program forces a page refresh or redirect. For example, refresh in an HTML <meta> tag, ASP.NET's Response.Redirect(), PHP's header(), etc.)

Long Running Upload Scripts

After Flash uploads a file to the web server, the upload receiving script is executed. The receiving script decides whether to store the files, create thumbnails, scan for viruses, etc. If the receiving script does not return any data within 30 seconds, Flash will disconnect the connection and return an IO error.

If you do not want this to happen, then during processing, have the server return a few characters or data (if you can).

For example with PHP, although the PHP script can continue to complete its operations successfully after Flash disconnects, Flash will not receive any returned data after the disconnection.

Window Mode WMODE / BUTTON_WINDOW_MODE

In some browsers, if the Flash control is not within the visible screen area, the set WMODE (configured by BUTTON_WINDOW_MODE) will prevent the Flash control from loading. Only when you scroll and bring the Flash control into the visible screen area will it load and render.

(yukon: This is done to make the page render as quickly as possible. For example, if you open a folder full of images, set the view mode to thumbnails, and scroll down quickly, you will see the image files below gradually display their content.)

This behavior may have an adverse effect on the SWFObject plugin. SWFUpload events may not be triggered, and the button's background image may not load until the control has rendered.

On some operating systems (Linux), when WMODE is set to transparent, the file selection dialog opened by Flash will appear behind the browser window.

Memory Leaks

Some browsers (especially IE) cannot reclaim memory after Flash Player uses the ExternalInterface class to interact with JS (for example, SWFUpload). Creating too many SWFUpload instances and refreshing the page several times will cause the browser to take up excessive memory, which in turn leads to browser crashes or other system errors.

In SWFUpload v2.2.0, we have implemented some mechanisms to prevent memory leaks. However, it is still recommended that you call the destroy() method when the page is closed. If you use hundreds of SWFUpload instances on a single page, you must test carefully to prevent memory leaks.

Some issues related to Mac OS — Other Mac Issues

  • The data returned by the server or Flash Player on Mac systems may not trigger the uploadSuccess event. We have added an assume_success_timeout setting to help resolve this issue. However, in general, it is very easy and reliable to return a short field after a successful receipt.
  • Some users have reported issues when uploading to addresses with a subdomain on Mac systems.
  • Some users have reported that redirects (HTTP status code 302) are not handled well by Mac Flash Player. There seems to be no such problem on Windows. 302 redirects are often used in some authorization modes and MVC design frameworks.
  • The Flash development documentation states that on systems earlier than OS X 10.3, bytes loaded will always be -1. SWFUpload changes it to 0, but total bytes will not be sent, and the progress will never reach 100%. Therefore, please update the UI to show 100% when the upload is complete and the uploadSuccess or uploadComplete event is fired. This keeps the UI consistent across all systems.
  • Some users have reported that Mac Flash Player has issues when the upload path contains space characters. Please replace them with + or %20.
  • Some users have reported that Mac Flash Player adds the port number to the HTTP HOST header (for example, http://www.example.com:80). If you check this parameter, be careful to handle this issue.
  • If a file contains only a resource fork, it will be treated by Flash Player as a 0-byte file and cannot be uploaded (Note: Flash Player 10.1 may have fixed this issue).