📄 uploader.as
字号:
package{ import com.yahoo.yui.YUIAdapter; import flash.display.Loader; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.DataEvent; import flash.events.Event; import flash.events.FocusEvent; import flash.events.HTTPStatusEvent; import flash.events.IOErrorEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.external.ExternalInterface; import flash.net.FileFilter; import flash.net.FileReference; import flash.net.FileReferenceList; import flash.net.URLRequest; import flash.net.URLVariables; import flash.ui.Keyboard; import flash.utils.Dictionary; [SWF(backgroundColor=0xffffff)] /** * The base Uploader class for YUI's Flash-based file uploader. * * @author Allen Rabinovich */ public class Uploader extends YUIAdapter { //-------------------------------------- // Constructor //-------------------------------------- public function Uploader() { super(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var allowMultiple:Boolean = false; private var allowLog:Boolean = false; private var filterArray:Array; private var fileDataList:Object; private var fileRefList:Object; private var fileIDList:Dictionary; private var fileIDCounter:Number; private var filesToUpload:Array; private var singleFile:FileReference; private var multipleFiles:FileReferenceList; /** * Determines how many files will be uploaded simultaneously * * @see setSimUploadLimit * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ public var simultaneousUploadLimit:Number = 2; // Track the number of current upload threads private var currentUploadThreads:Number = 0; // How the uploader is rendered, either "button" or "transparent" private var renderType:String; // The Sprite containing the rendered UI. private var buttonSprite:Sprite = new Sprite(); // The skin for the button, if "button" renderType is used. private var buttonSkin:Loader = new Loader(); // Height and width for the button private var buttonHeight:Number; private var buttonWidth:Number; //-------------------------------------- // Public Methods //-------------------------------------- /** * Sets the number of simultaneous file uploads possible. * The maximum is 5. * @param numberOfUploads Number of simultaneous uploads, no fewer than 1 * and no larger than 5. */ public function setSimUploadLimit (simUploadLimit:int) : void { if (simUploadLimit <= 1) { this.simultaneousUploadLimit = 1; } else if (simUploadLimit >= 5) { this.simultaneousUploadLimit = 5; } else { this.simultaneousUploadLimit = simUploadLimit; } } /** * Sets a list of file type filters for the "Open File(s)" dialog. * * @param newFilterArray An array of sets of key-value pairs of the form * {extensions: extensionString, description: descriptionString, macType: macTypeString [optional]} * The extension string is a semicolon-delimited list of elements of the form "*.xxx", * e.g. "*.jpg;*.gif;*.png". */ public function setFileFilters(newFilterArray:Array) : void { filterArray = processFileFilterObjects(newFilterArray); if (allowLog) { var logString:String = "File filters have been set to the following: \n"; for each (var ff:FileFilter in filterArray) { logString += ff.extension + ": " + ff.description + "\n"; } logMessage(logString); } } /** * Sets a flag allowing logging in Flash trace and Yahoo logger. * * @param allowLogging Whether to allow log messages. * */ public function setAllowLogging(allowLogging:Boolean) : void { this.allowLog = allowLogging; logMessage("Logging has been turned " + (allowLog ? "on." : "off.")); } /** * Sets a flag allowing multiple file selection in the "Browse" dialog. * * @param allowMultiple Whether to allow multiple file selection. * */ public function setAllowMultipleFiles(allowMultipleFiles:Boolean) : void { this.allowMultiple = allowMultipleFiles; logMessage("Multiple file upload has been turned " + (allowMultiple ? "on." : "off.")); } /** * Triggers a prompt for the user to browse their file system to select * files to be uploaded. * * @param allowMultiple Whether to allow the user to select more than * one file * * @param filterArray An array of filter objects, each with <code> * description</code>, and <code>extensions</code> properties which * determine which files the user is allowed to select */ private function browse(allowMultiple:Boolean = false, filterArray:Array = null):void { if(!allowMultiple) { logMessage("Browsing for a single file.") singleFile = new FileReference(); singleFile.addEventListener(Event.SELECT, singleFileSelected); if(filterArray) { singleFile.browse(filterArray); } else { singleFile.browse(); } } else { logMessage("Browsing for one or more files.") multipleFiles = new FileReferenceList(); multipleFiles.addEventListener(Event.SELECT, multipleFilesSelected); if(filterArray) { multipleFiles.browse(filterArray); } else { multipleFiles.browse(); } } } /** * Removes the file from the set to be uploaded * * @param fileID The ID of the file to be removed */ public function removeFile(fileID:String):Object { // TODO: Do we need to remove the item from filesToUpload also? delete fileDataList[fileID]; delete fileRefList[fileID]; return fileDataList; } public function enable () : void { if (renderType == "button") { this.addEventListener(MouseEvent.ROLL_OVER, buttonMouseOver); this.addEventListener(MouseEvent.ROLL_OUT, buttonMouseOut); this.addEventListener(MouseEvent.MOUSE_DOWN, buttonMouseDown); this.addEventListener(MouseEvent.MOUSE_UP, buttonMouseUp); this.addEventListener(MouseEvent.CLICK, handleMouseClick); buttonSkin.y = 0; } else { this.addEventListener(MouseEvent.CLICK, handleMouseClick); this.addEventListener(MouseEvent.CLICK, transparentClick); this.addEventListener(MouseEvent.MOUSE_DOWN, transparentDown); this.addEventListener(MouseEvent.MOUSE_UP, transparentUp); this.addEventListener(MouseEvent.ROLL_OVER, transparentRollOver); this.addEventListener(MouseEvent.ROLL_OUT, transparentRollOut); } logMessage("Uploader UI has been enabled."); } public function disable () : void { if (renderType == "button") { this.removeEventListener(MouseEvent.ROLL_OVER, buttonMouseOver); this.removeEventListener(MouseEvent.ROLL_OUT, buttonMouseOut); this.removeEventListener(MouseEvent.MOUSE_DOWN, buttonMouseDown); this.removeEventListener(MouseEvent.MOUSE_UP, buttonMouseUp); this.removeEventListener(MouseEvent.CLICK, handleMouseClick); buttonSkin.y = -3*buttonHeight; } else { this.removeEventListener(MouseEvent.CLICK, handleMouseClick); this.removeEventListener(MouseEvent.CLICK, transparentClick); this.removeEventListener(MouseEvent.MOUSE_DOWN, transparentDown); this.removeEventListener(MouseEvent.MOUSE_UP, transparentUp); this.removeEventListener(MouseEvent.ROLL_OVER, transparentRollOver); this.removeEventListener(MouseEvent.ROLL_OUT, transparentRollOut); } logMessage("Uploader UI has been disabled."); } /** * Clears the set of files that had been selected for upload */ public function clearFileList():Boolean { // TODO: Remove event listeners (or weak references?) filesToUpload = []; fileDataList = new Object(); fileRefList = new Object(); fileIDList = new Dictionary(); fileIDCounter = 0; logMessage("The file list has been cleared."); return true; } /** * Uploads a file corresponding to a specified ID to a specified path where a script handles writing to the server. * * @param fileID The ID of the file to be uploaded * @param url The path to the serverside script * @param method The HTTP submission method. Possible values are "GET" and "POST" * @param vars An object containing variables to be sent along with the request * @param fieldName The field name that precedes the file data in the upload POST operation. * The uploadDataFieldName value must be non-null and a non-empty String. * @param headers An object containing variables that should be set as headers in the POST request. The following header names * cannot be used: * <code> * Accept-Charset, Accept-Encoding, Accept-Ranges, Age, Allow, Allowed, Authorization, Charge-To, Connect, Connection, * Content-Length, Content-Location, Content-Range, Cookie, Date, Delete, ETag, Expect, Get, Head, Host, Keep-Alive, * Last-Modified, Location, Max-Forwards, Options, Post, Proxy-Authenticate, Proxy-Authorization, Proxy-Connection, * Public, Put, Range, Referer, Request-Range, Retry-After, Server, TE, Trace, Trailer, Transfer-Encoding, Upgrade, * URI, User-Agent, Vary, Via, Warning, WWW-Authenticate, x-flash-version. * </code> */ public function upload(fileID:String, url:String, method:String = "GET", vars:Object = null, fieldName:String = "Filedata"):void { // null checking in the params is not working correctly filesToUpload = []; if(isEmptyString(method)) { method = "GET"; } if(isEmptyString(fieldName)) { fieldName = "Filedata"; } var request:URLRequest = formURLRequest(url, method, vars); var fr:FileReference = fileRefList[fileID]; this.currentUploadThreads++; fr.upload(request,fieldName); } /** * Uploads all files to a specified path where a script handles writing to the server. * * @param fileID The ID of the file to be uploaded * @param url The path to the serverside script * @param method The HTTP submission method. Possible values are "GET" and "POST" * @param vars An object containing data to be sent along with the request * @param fieldName The field name that precedes the file data in the upload POST operation. The uploadDataFieldName value must be non-null and a non-empty String. * @param headers An object containing variables that should be set as headers in the POST request. The following header names * cannot be used: * <code> * Accept-Charset, Accept-Encoding, Accept-Ranges, Age, Allow, Allowed, Authorization, Charge-To, Connect, Connection, * Content-Length, Content-Location, Content-Range, Cookie, Date, Delete, ETag, Expect, Get, Head, Host, Keep-Alive, * Last-Modified, Location, Max-Forwards, Options, Post, Proxy-Authenticate, Proxy-Authorization, Proxy-Connection, * Public, Put, Range, Referer, Request-Range, Retry-After, Server, TE, Trace, Trailer, Transfer-Encoding, Upgrade, * URI, User-Agent, Vary, Via, Warning, WWW-Authenticate, x-flash-version. * </code> */ public function uploadAll(url:String, method:String = "GET", vars:Object = null, fieldName:String = "Filedata", headers:Object = null):void { if(isEmptyString(method)) { method = "GET"; } if(isEmptyString(fieldName)) { fieldName = "Filedata"; } var request:URLRequest = formURLRequest(url, method, vars); for each(var fr:FileReference in fileRefList) { queueForUpload(fr, request, fieldName); } processQueue(); } /** * Cancels either an upload of the file corresponding to a given fileID, or in the absence of the specified fileID, all active files being uploaded. * * @param fileID The ID of the file to be uploaded */ public function cancel(fileID:String = null):void { logMessage("Canceling upload"); if (fileID == null) { // cancel all files for each (var item:FileReference in fileRefList) { item.cancel(); } } else { // cancel specified file var fr:FileReference = fileRefList[fileID]; fr.cancel(); } } /* Events ------------------------------- mouseDown - fires when the mouse button is pressed over uploader mouseUp - fires when the mouse button is released over uploader rollOver - fires when the mouse rolls over the uploader rollOut - fires when the mouse rolls out of the uploader click - fires when the uploader is clicked fileSelect - fires when the user selects one or more files (after browse is called). Passes the array of currently selected files (if prior browse calls were made and clearFileList hasn't been called, all files the user has ever selected will be returned), along with all information available about them (name, size, type, creationDate, modificationDate, creator). uploadStart - fires when a file starts uploading. Passes a file id for identifying the file. uploadProgress - fires when a file upload reports progress. Passes the file id, as well as bytesUploaded and bytesTotal for the given file. uploadComplete - fires when a file upload is completed successfully and passes the corresponding file id. uploadCompleteData - fires when data is received from the server after upload and passes the corresponding file id and the said data. uploadError - fires when an error occurs during download. Passes the id of the file that was being uploaded and an error type. */ private function transparentDown (event:MouseEvent) : void { logMessage("Mouse down on the uploader."); var newEvent:Object = new Object(); newEvent.type = "mouseDown"; super.dispatchEventToJavaScript(newEvent); } private function transparentUp (event:MouseEvent) : void { logMessage("Mouse up on the uploader."); var newEvent:Object = new Object(); newEvent.type = "mouseUp"; super.dispatchEventToJavaScript(newEvent); } private function transparentRollOver (event:MouseEvent) : void { logMessage("Mouse rolled over the uploader."); var newEvent:Object = new Object(); newEvent.type = "rollOver"; super.dispatchEventToJavaScript(newEvent); } private function transparentRollOut (event:MouseEvent) : void { logMessage("Mouse rolled out the uploader."); var newEvent:Object = new Object(); newEvent.type = "rollOut"; super.dispatchEventToJavaScript(newEvent); } private function transparentClick (event:MouseEvent) : void { logMessage("Mouse clicked on the uploader."); var newEvent:Object = new Object(); newEvent.type = "click"; super.dispatchEventToJavaScript(newEvent); } private function uploadStart (event:Event) : void { logMessage("Started upload for " + fileIDList[event.target]); var newEvent:Object = new Object(); newEvent.id = fileIDList[event.target]; newEvent.type = "uploadStart"; super.dispatchEventToJavaScript(newEvent); } private function uploadProgress (event:ProgressEvent) : void { logMessage("Progress for " + fileIDList[event.target] + ": " + event.bytesLoaded.toString() + " / " + event.bytesTotal.toString()); var newEvent:Object = new Object(); newEvent.id = fileIDList[event.target]; newEvent.bytesLoaded = event.bytesLoaded; newEvent.bytesTotal = event.bytesTotal; newEvent.type = "uploadProgress" super.dispatchEventToJavaScript(newEvent); } private function uploadComplete (event:Event) : void { logMessage("Upload complete for " + fileIDList[event.target]); var newEvent:Object = new Object(); newEvent.id = fileIDList[event.target]; newEvent.type = "uploadComplete"
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -