PageRenderTime 119ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/system/application/views/admin/static/js/swfupload/swfupload_fp9/SWFUpload.as

https://github.com/isS/Microweber
ActionScript | 1227 lines | 923 code | 196 blank | 108 comment | 182 complexity | 15768fb5928976c8d8f32ddd916416a7 MD5 | raw file
  1. /* Todo:
  2. * Missing initial progress event
  3. * Improve resizing/encoding so it doesn't lock up browser.
  4. * */
  5. package {
  6. import flash.display.BlendMode;
  7. import flash.display.DisplayObjectContainer;
  8. import flash.display.Loader;
  9. import flash.display.Stage;
  10. import flash.display.Sprite;
  11. import flash.display.StageAlign;
  12. import flash.display.StageScaleMode;
  13. import flash.net.FileReferenceList;
  14. import flash.net.FileReference;
  15. import flash.net.FileFilter;
  16. import flash.net.URLRequest;
  17. import flash.net.URLRequestMethod;
  18. import flash.net.URLVariables;
  19. import flash.events.*;
  20. import flash.external.ExternalInterface;
  21. import flash.system.Security;
  22. import flash.text.AntiAliasType;
  23. import flash.text.GridFitType;
  24. import flash.text.StaticText;
  25. import flash.text.StyleSheet;
  26. import flash.text.TextDisplayMode;
  27. import flash.text.TextField;
  28. import flash.text.TextFieldType;
  29. import flash.text.TextFieldAutoSize;
  30. import flash.text.TextFormat;
  31. import flash.ui.Mouse;
  32. import flash.utils.ByteArray;
  33. import flash.utils.Timer;
  34. import FileItem;
  35. import ExternalCall;
  36. public class SWFUpload extends Sprite {
  37. // Cause SWFUpload to start as soon as the movie starts
  38. public static function main():void
  39. {
  40. var SWFUpload:SWFUpload = new SWFUpload();
  41. }
  42. private const build_number:String = "2.5.0 FP9 2010-01-15 Beta 2";
  43. // State tracking variables
  44. private var fileBrowserMany:FileReferenceList = new FileReferenceList();
  45. private var fileBrowserOne:FileReference = null; // This isn't set because it can't be reused like the FileReferenceList. It gets setup in the SelectFile method
  46. private var file_queue:Array = new Array(); // holds a list of all items that are to be uploaded.
  47. private var current_file_item:FileItem = null; // the item that is currently being uploaded.
  48. private var file_index:Array = new Array();
  49. private var successful_uploads:Number = 0; // Tracks the uploads that have been completed
  50. private var queue_errors:Number = 0; // Tracks files rejected during queueing
  51. private var upload_errors:Number = 0; // Tracks files that fail upload
  52. private var upload_cancelled:Number = 0; // Tracks number of cancelled files
  53. private var queued_uploads:Number = 0; // Tracks the FileItems that are waiting to be uploaded.
  54. private var valid_file_extensions:Array = new Array();// Holds the parsed valid extensions.
  55. private var serverDataTimer:Timer = null;
  56. private var assumeSuccessTimer:Timer = null;
  57. private var sizeTimer:Timer;
  58. private var hasCalledFlashReady:Boolean = false;
  59. // Callbacks
  60. private var flashReady_Callback:String;
  61. private var fileDialogStart_Callback:String;
  62. private var fileQueued_Callback:String;
  63. private var fileQueueError_Callback:String;
  64. private var fileDialogComplete_Callback:String;
  65. private var uploadStart_Callback:String;
  66. private var uploadProgress_Callback:String;
  67. private var uploadError_Callback:String;
  68. private var uploadSuccess_Callback:String;
  69. private var uploadComplete_Callback:String;
  70. private var debug_Callback:String;
  71. private var mouseOut_Callback:String;
  72. private var mouseOver_Callback:String;
  73. private var mouseClick_Callback:String;
  74. // Values passed in from the HTML
  75. private var movieName:String;
  76. private var uploadURL:String;
  77. private var filePostName:String;
  78. private var uploadPostObject:Object;
  79. private var fileTypes:String;
  80. private var fileTypesDescription:String;
  81. private var fileSizeLimit:Number;
  82. private var fileUploadLimit:Number = 0;
  83. private var fileQueueLimit:Number = 0;
  84. private var useQueryString:Boolean = false;
  85. private var requeueOnError:Boolean = false;
  86. private var httpSuccess:Array = [];
  87. private var assumeSuccessTimeout:Number = 0;
  88. private var debugEnabled:Boolean;
  89. private var buttonLoader:Loader;
  90. private var buttonTextField:TextField;
  91. private var buttonCursorSprite:Sprite;
  92. private var buttonImageURL:String;
  93. //private var buttonWidth:Number;
  94. //private var buttonHeight:Number;
  95. private var buttonText:String;
  96. private var buttonTextStyle:String;
  97. private var buttonTextTopPadding:Number;
  98. private var buttonTextLeftPadding:Number;
  99. private var buttonAction:Number;
  100. private var buttonCursor:Number;
  101. private var buttonStateOver:Boolean;
  102. private var buttonStateMouseDown:Boolean;
  103. private var buttonStateDisabled:Boolean;
  104. // Error code "constants"
  105. // Size check constants
  106. private var SIZE_TOO_BIG:Number = 1;
  107. private var SIZE_ZERO_BYTE:Number = -1;
  108. private var SIZE_OK:Number = 0;
  109. // Queue errors
  110. private var ERROR_CODE_QUEUE_LIMIT_EXCEEDED:Number = -100;
  111. private var ERROR_CODE_FILE_EXCEEDS_SIZE_LIMIT:Number = -110;
  112. private var ERROR_CODE_ZERO_BYTE_FILE:Number = -120;
  113. private var ERROR_CODE_INVALID_FILETYPE:Number = -130;
  114. // Upload Errors
  115. private var ERROR_CODE_HTTP_ERROR:Number = -200;
  116. private var ERROR_CODE_MISSING_UPLOAD_URL:Number = -210;
  117. private var ERROR_CODE_IO_ERROR:Number = -220;
  118. private var ERROR_CODE_SECURITY_ERROR:Number = -230;
  119. private var ERROR_CODE_UPLOAD_LIMIT_EXCEEDED:Number = -240;
  120. private var ERROR_CODE_UPLOAD_FAILED:Number = -250;
  121. private var ERROR_CODE_SPECIFIED_FILE_ID_NOT_FOUND:Number = -260;
  122. private var ERROR_CODE_FILE_VALIDATION_FAILED:Number = -270;
  123. private var ERROR_CODE_FILE_CANCELLED:Number = -280;
  124. private var ERROR_CODE_UPLOAD_STOPPED:Number = -290;
  125. // Button Actions
  126. private var BUTTON_ACTION_SELECT_FILE:Number = -100;
  127. private var BUTTON_ACTION_SELECT_FILES:Number = -110;
  128. private var BUTTON_ACTION_START_UPLOAD:Number = -120;
  129. private var BUTTON_ACTION_NONE:Number = -130;
  130. private var BUTTON_ACTION_JAVASCRIPT:Number = -130; // DEPRECATED
  131. private var BUTTON_CURSOR_ARROW:Number = -1;
  132. private var BUTTON_CURSOR_HAND:Number = -2;
  133. public function SWFUpload() {
  134. // Do the feature detection. Make sure this version of Flash supports the features we need. If not
  135. // abort initialization.
  136. if (!flash.net.FileReferenceList || !flash.net.FileReference || !flash.net.URLRequest || !flash.external.ExternalInterface || !flash.external.ExternalInterface.available || !DataEvent.UPLOAD_COMPLETE_DATA) {
  137. return;
  138. }
  139. var self:SWFUpload = this;
  140. Security.allowDomain("*"); // Allow uploading to any domain
  141. Security.allowInsecureDomain("*"); // Allow uploading from HTTP to HTTPS and HTTPS to HTTP
  142. // Keep Flash Player busy so it doesn't show the "flash script is running slowly" error
  143. var counter:Number = 0;
  144. root.addEventListener(Event.ENTER_FRAME, function ():void { if (++counter > 100) counter = 0; });
  145. // Setup file FileReferenceList events
  146. this.fileBrowserMany.addEventListener(Event.SELECT, this.Select_Many_Handler);
  147. this.fileBrowserMany.addEventListener(Event.CANCEL, this.DialogCancelled_Handler);
  148. this.stage.align = StageAlign.TOP_LEFT;
  149. this.stage.scaleMode = StageScaleMode.NO_SCALE;
  150. this.stage.addEventListener(Event.RESIZE, function (e:Event):void {
  151. self.HandleStageResize(e);
  152. });
  153. // Setup the button and text label
  154. this.buttonLoader = new Loader();
  155. var doNothing:Function = function ():void { };
  156. this.buttonLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, doNothing );
  157. this.buttonLoader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, doNothing );
  158. this.buttonLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.ButtonImageLoaded );
  159. this.stage.addChild(this.buttonLoader);
  160. this.stage.addEventListener(MouseEvent.CLICK, function (event:MouseEvent):void {
  161. self.UpdateButtonState();
  162. self.ButtonClickHandler(event);
  163. });
  164. this.stage.addEventListener(MouseEvent.MOUSE_DOWN, function (event:MouseEvent):void {
  165. self.buttonStateMouseDown = true;
  166. self.UpdateButtonState();
  167. });
  168. this.stage.addEventListener(MouseEvent.MOUSE_UP, function (event:MouseEvent):void {
  169. self.buttonStateMouseDown = false;
  170. self.UpdateButtonState();
  171. });
  172. this.stage.addEventListener(MouseEvent.MOUSE_OVER, function (event:MouseEvent):void {
  173. self.buttonStateMouseDown = event.buttonDown;
  174. self.buttonStateOver = true;
  175. self.UpdateButtonState();
  176. ExternalCall.Simple(self.mouseOver_Callback);
  177. });
  178. this.stage.addEventListener(MouseEvent.MOUSE_OUT, function (event:MouseEvent):void {
  179. self.buttonStateMouseDown = false;
  180. self.buttonStateOver = false;
  181. self.UpdateButtonState();
  182. });
  183. // Handle the mouse leaving the flash movie altogether
  184. this.stage.addEventListener(Event.MOUSE_LEAVE, function (event:Event):void {
  185. self.buttonStateMouseDown = false;
  186. self.buttonStateOver = false;
  187. self.UpdateButtonState();
  188. ExternalCall.Simple(self.mouseOut_Callback);
  189. });
  190. this.buttonTextField = new TextField();
  191. this.buttonTextField.type = TextFieldType.DYNAMIC;
  192. this.buttonTextField.antiAliasType = AntiAliasType.ADVANCED;
  193. this.buttonTextField.autoSize = TextFieldAutoSize.NONE;
  194. this.buttonTextField.cacheAsBitmap = true;
  195. this.buttonTextField.multiline = true;
  196. this.buttonTextField.wordWrap = false;
  197. this.buttonTextField.tabEnabled = false;
  198. this.buttonTextField.background = false;
  199. this.buttonTextField.border = false;
  200. this.buttonTextField.selectable = false;
  201. this.buttonTextField.condenseWhite = true;
  202. this.stage.addChild(this.buttonTextField);
  203. this.buttonCursorSprite = new Sprite();
  204. this.buttonCursorSprite.graphics.beginFill(0xFFFFFF, 0);
  205. this.buttonCursorSprite.graphics.drawRect(0, 0, 1, 1);
  206. this.buttonCursorSprite.graphics.endFill();
  207. this.buttonCursorSprite.buttonMode = true;
  208. this.buttonCursorSprite.x = 0;
  209. this.buttonCursorSprite.y = 0;
  210. this.buttonCursorSprite.addEventListener(MouseEvent.CLICK, doNothing);
  211. this.stage.addChild(this.buttonCursorSprite);
  212. this.sizeTimer = new Timer(10, 0);
  213. this.sizeTimer.addEventListener(TimerEvent.TIMER, function ():void {
  214. //self.Debug("Stage:" + self.stage.stageWidth + " by " + self.stage.stageHeight);
  215. if (self.stage.stageWidth > 0 || self.stage.stageHeight > 0) {
  216. self.HandleStageResize(null);
  217. self.sizeTimer.stop();
  218. self.sizeTimer.removeEventListener(TimerEvent.TIMER, arguments.callee);
  219. self.sizeTimer = null;
  220. }
  221. } );
  222. this.sizeTimer.start();
  223. // Get the movie name
  224. this.movieName = decodeURIComponent(root.loaderInfo.parameters.movieName);
  225. // **Configure the callbacks**
  226. // The JavaScript tracks all the instances of SWFUpload on a page. We can access the instance
  227. // associated with this SWF file using the movieName. Each callback is accessible by making
  228. // a call directly to it on our instance. There is no error handling for undefined callback functions.
  229. // A developer would have to deliberately remove the default functions,set the variable to null, or remove
  230. // it from the init function.
  231. this.flashReady_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].flashReady";
  232. this.fileDialogStart_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].fileDialogStart";
  233. this.fileQueued_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].fileQueued";
  234. this.fileQueueError_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].fileQueueError";
  235. this.fileDialogComplete_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].fileDialogComplete";
  236. this.uploadStart_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadStart";
  237. this.uploadProgress_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadProgress";
  238. this.uploadError_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadError";
  239. this.uploadSuccess_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadSuccess";
  240. this.uploadComplete_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadComplete";
  241. this.debug_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].debug";
  242. this.mouseOut_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].mouseOut";
  243. this.mouseOver_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].mouseOver";
  244. this.mouseClick_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].mouseClick";
  245. // Get the Flash Vars
  246. this.uploadURL = decodeURIComponent(root.loaderInfo.parameters.uploadURL);
  247. this.filePostName = decodeURIComponent(root.loaderInfo.parameters.filePostName);
  248. this.fileTypes = decodeURIComponent(root.loaderInfo.parameters.fileTypes);
  249. this.fileTypesDescription = decodeURIComponent(root.loaderInfo.parameters.fileTypesDescription) + " (" + this.fileTypes + ")";
  250. this.loadPostParams(decodeURIComponent(root.loaderInfo.parameters.params));
  251. if (!this.filePostName) {
  252. this.filePostName = "Filedata";
  253. }
  254. if (!this.fileTypes) {
  255. this.fileTypes = "*.*";
  256. }
  257. if (!this.fileTypesDescription) {
  258. this.fileTypesDescription = "All Files";
  259. }
  260. this.LoadFileExensions(this.fileTypes);
  261. try {
  262. this.debugEnabled = decodeURIComponent(root.loaderInfo.parameters.debugEnabled) == "true" ? true : false;
  263. } catch (ex:Object) {
  264. this.debugEnabled = false;
  265. }
  266. try {
  267. this.SetFileSizeLimit(String(decodeURIComponent(root.loaderInfo.parameters.fileSizeLimit)));
  268. } catch (ex:Object) {
  269. this.fileSizeLimit = 0;
  270. }
  271. try {
  272. this.fileUploadLimit = Number(decodeURIComponent(root.loaderInfo.parameters.fileUploadLimit));
  273. if (this.fileUploadLimit < 0) this.fileUploadLimit = 0;
  274. } catch (ex:Object) {
  275. this.fileUploadLimit = 0;
  276. }
  277. try {
  278. this.fileQueueLimit = Number(decodeURIComponent(root.loaderInfo.parameters.fileQueueLimit));
  279. if (this.fileQueueLimit < 0) this.fileQueueLimit = 0;
  280. } catch (ex:Object) {
  281. this.fileQueueLimit = 0;
  282. }
  283. // Set the queue limit to match the upload limit when the queue limit is bigger than the upload limit
  284. if (this.fileQueueLimit > this.fileUploadLimit && this.fileUploadLimit != 0) this.fileQueueLimit = this.fileUploadLimit;
  285. // The the queue limit is unlimited and the upload limit is not then set the queue limit to the upload limit
  286. if (this.fileQueueLimit == 0 && this.fileUploadLimit != 0) this.fileQueueLimit = this.fileUploadLimit;
  287. try {
  288. this.useQueryString = decodeURIComponent(root.loaderInfo.parameters.useQueryString) == "true" ? true : false;
  289. } catch (ex:Object) {
  290. this.useQueryString = false;
  291. }
  292. try {
  293. this.requeueOnError = decodeURIComponent(root.loaderInfo.parameters.requeueOnError) == "true" ? true : false;
  294. } catch (ex:Object) {
  295. this.requeueOnError = false;
  296. }
  297. try {
  298. this.SetHTTPSuccess(String(decodeURIComponent(root.loaderInfo.parameters.httpSuccess)));
  299. } catch (ex:Object) {
  300. this.SetHTTPSuccess([]);
  301. }
  302. try {
  303. this.SetAssumeSuccessTimeout(Number(decodeURIComponent(root.loaderInfo.parameters.assumeSuccessTimeout)));
  304. } catch (ex:Object) {
  305. this.SetAssumeSuccessTimeout(0);
  306. }
  307. try {
  308. this.SetButtonImageURL(String(decodeURIComponent(root.loaderInfo.parameters.buttonImageURL)));
  309. } catch (ex:Object) {
  310. this.SetButtonImageURL("");
  311. }
  312. try {
  313. this.SetButtonText(String(decodeURIComponent(root.loaderInfo.parameters.buttonText)));
  314. } catch (ex:Object) {
  315. this.SetButtonText("");
  316. }
  317. try {
  318. this.SetButtonTextPadding(Number(decodeURIComponent(root.loaderInfo.parameters.buttonTextLeftPadding)), Number(decodeURIComponent(root.loaderInfo.parameters.buttonTextTopPadding)));
  319. } catch (ex:Object) {
  320. this.SetButtonTextPadding(0, 0);
  321. }
  322. try {
  323. this.SetButtonTextStyle(String(decodeURIComponent(root.loaderInfo.parameters.buttonTextStyle)));
  324. } catch (ex:Object) {
  325. this.SetButtonTextStyle("");
  326. }
  327. try {
  328. this.SetButtonAction(Number(decodeURIComponent(root.loaderInfo.parameters.buttonAction)));
  329. } catch (ex:Object) {
  330. this.SetButtonAction(this.BUTTON_ACTION_SELECT_FILES);
  331. }
  332. try {
  333. this.SetButtonDisabled(decodeURIComponent(root.loaderInfo.parameters.buttonDisabled) == "true" ? true : false);
  334. } catch (ex:Object) {
  335. this.SetButtonDisabled(Boolean(false));
  336. }
  337. try {
  338. this.SetButtonCursor(Number(decodeURIComponent(root.loaderInfo.parameters.buttonCursor)));
  339. } catch (ex:Object) {
  340. this.SetButtonCursor(this.BUTTON_CURSOR_ARROW);
  341. }
  342. this.SetupExternalInterface();
  343. this.Debug("SWFUpload Init Complete");
  344. this.PrintDebugInfo();
  345. ExternalCall.Simple(this.flashReady_Callback);
  346. this.hasCalledFlashReady = true;
  347. }
  348. private function HandleStageResize(e:Event):void {
  349. if (this.stage.stageWidth > 0 || this.stage.stageHeight > 0) {
  350. this.Debug("Stage Resize:" + this.stage.stageWidth + " by " + this.stage.stageHeight);
  351. // scale the button (if it's not loaded don't crash)
  352. try {
  353. var buttonHeight:Number = this.buttonLoader.contentLoaderInfo.height / 4;
  354. this.buttonLoader.height = this.stage.stageHeight * 4;
  355. this.buttonLoader.scaleX = this.buttonLoader.scaleY;
  356. } catch (ex:Error) { }
  357. // Scale the button cursor
  358. try {
  359. this.buttonCursorSprite.width = this.stage.stageWidth;
  360. this.buttonCursorSprite.height = this.stage.stageHeight;
  361. } catch (ex:Error) {}
  362. // scale the text area (it doesn't resize but it still needs to fit)
  363. try {
  364. this.buttonTextField.width = this.stage.stageWidth;
  365. this.buttonTextField.height = this.stage.stageHeight;
  366. } catch (ex:Error) {}
  367. }
  368. }
  369. private function SetupExternalInterface():void {
  370. try {
  371. ExternalInterface.addCallback("SelectFile", this.SelectFile);
  372. ExternalInterface.addCallback("SelectFiles", this.SelectFiles);
  373. ExternalInterface.addCallback("StartUpload", this.StartUpload);
  374. ExternalInterface.addCallback("ReturnUploadStart", this.ReturnUploadStart);
  375. ExternalInterface.addCallback("StopUpload", this.StopUpload);
  376. ExternalInterface.addCallback("CancelUpload", this.CancelUpload);
  377. ExternalInterface.addCallback("RequeueUpload", this.RequeueUpload);
  378. ExternalInterface.addCallback("GetStats", this.GetStats);
  379. ExternalInterface.addCallback("SetStats", this.SetStats);
  380. ExternalInterface.addCallback("GetFile", this.GetFile);
  381. ExternalInterface.addCallback("GetFileByIndex", this.GetFileByIndex);
  382. ExternalInterface.addCallback("GetFileByQueueIndex", this.GetFileByQueueIndex);
  383. ExternalInterface.addCallback("AddFileParam", this.AddFileParam);
  384. ExternalInterface.addCallback("RemoveFileParam", this.RemoveFileParam);
  385. ExternalInterface.addCallback("SetUploadURL", this.SetUploadURL);
  386. ExternalInterface.addCallback("SetPostParams", this.SetPostParams);
  387. ExternalInterface.addCallback("SetFileTypes", this.SetFileTypes);
  388. ExternalInterface.addCallback("SetFileSizeLimit", this.SetFileSizeLimit);
  389. ExternalInterface.addCallback("SetFileUploadLimit", this.SetFileUploadLimit);
  390. ExternalInterface.addCallback("SetFileQueueLimit", this.SetFileQueueLimit);
  391. ExternalInterface.addCallback("SetFilePostName", this.SetFilePostName);
  392. ExternalInterface.addCallback("SetUseQueryString", this.SetUseQueryString);
  393. ExternalInterface.addCallback("SetRequeueOnError", this.SetRequeueOnError);
  394. ExternalInterface.addCallback("SetHTTPSuccess", this.SetHTTPSuccess);
  395. ExternalInterface.addCallback("SetAssumeSuccessTimeout", this.SetAssumeSuccessTimeout);
  396. ExternalInterface.addCallback("SetDebugEnabled", this.SetDebugEnabled);
  397. ExternalInterface.addCallback("SetButtonImageURL", this.SetButtonImageURL);
  398. ExternalInterface.addCallback("SetButtonText", this.SetButtonText);
  399. ExternalInterface.addCallback("SetButtonTextPadding", this.SetButtonTextPadding);
  400. ExternalInterface.addCallback("SetButtonTextStyle", this.SetButtonTextStyle);
  401. ExternalInterface.addCallback("SetButtonAction", this.SetButtonAction);
  402. ExternalInterface.addCallback("SetButtonDisabled", this.SetButtonDisabled);
  403. ExternalInterface.addCallback("SetButtonCursor", this.SetButtonCursor);
  404. } catch (ex:Error) {
  405. this.Debug("Callbacks where not set: " + ex.message);
  406. return;
  407. }
  408. }
  409. /* *****************************************
  410. * FileReference Event Handlers
  411. * *************************************** */
  412. private function DialogCancelled_Handler(event:Event):void {
  413. this.Debug("Event: fileDialogComplete: File Dialog window cancelled.");
  414. ExternalCall.FileDialogComplete(this.fileDialogComplete_Callback, 0, 0, this.queued_uploads);
  415. }
  416. private function Open_Handler(event:Event):void {
  417. this.Debug("Event: uploadProgress (OPEN): File ID: " + this.current_file_item.id);
  418. this.current_file_item.finalUploadProgress = false;
  419. ExternalCall.UploadProgress(this.uploadProgress_Callback, this.current_file_item.ToJavaScriptObject(), 0, this.current_file_item.file_reference.size);
  420. }
  421. private function FileProgress_Handler(event:ProgressEvent):void {
  422. // On early than Mac OS X 10.3 bytesLoaded is always -1, convert this to zero. Do bytesTotal for good measure.
  423. // http://livedocs.adobe.com/flex/3/langref/flash/net/FileReference.html#event:progress
  424. var bytesLoaded:Number = event.bytesLoaded < 0 ? 0 : event.bytesLoaded;
  425. var bytesTotal:Number = event.bytesTotal < 0 ? 0 : event.bytesTotal;
  426. // Because Flash never fires a complete event if the server doesn't respond after 30 seconds or on Macs if there
  427. // is no content in the response we'll set a timer and assume that the upload is successful after the defined amount of
  428. // time. If the timeout is zero then we won't use the timer.
  429. if (bytesLoaded === bytesTotal) {
  430. this.current_file_item.finalUploadProgress = true;
  431. if (bytesTotal > 0 && this.assumeSuccessTimeout > 0) {
  432. if (this.assumeSuccessTimer !== null) {
  433. this.assumeSuccessTimer.stop();
  434. this.assumeSuccessTimer = null;
  435. }
  436. this.assumeSuccessTimer = new Timer(this.assumeSuccessTimeout * 1000, 1);
  437. this.assumeSuccessTimer.addEventListener(TimerEvent.TIMER_COMPLETE, AssumeSuccessTimer_Handler);
  438. this.assumeSuccessTimer.start();
  439. }
  440. }
  441. this.Debug("Event: uploadProgress: File ID: " + this.current_file_item.id + ". Bytes: " + bytesLoaded + ". Total: " + bytesTotal);
  442. ExternalCall.UploadProgress(this.uploadProgress_Callback, this.current_file_item.ToJavaScriptObject(), bytesLoaded, bytesTotal);
  443. }
  444. private function AssumeSuccessTimer_Handler(event:TimerEvent):void {
  445. this.Debug("Event: AssumeSuccess: " + this.assumeSuccessTimeout + " passed without server response");
  446. this.UploadSuccess(this.current_file_item, "", false);
  447. }
  448. private function Complete_Handler(event:Event):void {
  449. /* Because we can't do COMPLETE or DATA events (we have to do both) we can't
  450. * just call uploadSuccess from the complete handler, we have to wait for
  451. * the Data event which may never come. However, testing shows it always comes
  452. * within a couple milliseconds if it is going to come so the solution is:
  453. *
  454. * Set a timer in the COMPLETE event (which always fires) and if DATA is fired
  455. * it will stop the timer and call uploadComplete
  456. *
  457. * If the timer expires then DATA won't be fired and we call uploadComplete
  458. * */
  459. // Set the timer
  460. if (serverDataTimer != null) {
  461. this.serverDataTimer.stop();
  462. this.serverDataTimer = null;
  463. }
  464. this.serverDataTimer = new Timer(100, 1);
  465. //var self:SWFUpload = this;
  466. this.serverDataTimer.addEventListener(TimerEvent.TIMER, this.ServerDataTimer_Handler);
  467. this.serverDataTimer.start();
  468. }
  469. private function ServerDataTimer_Handler(event:TimerEvent):void {
  470. this.UploadSuccess(this.current_file_item, "");
  471. }
  472. private function ServerData_Handler(event:DataEvent):void {
  473. this.UploadSuccess(this.current_file_item, event.data);
  474. }
  475. private function UploadSuccess(file:FileItem, serverData:String, responseReceived:Boolean = true):void {
  476. if (this.serverDataTimer !== null) {
  477. this.serverDataTimer.stop();
  478. this.serverDataTimer = null;
  479. }
  480. if (this.assumeSuccessTimer !== null) {
  481. this.assumeSuccessTimer.stop();
  482. this.assumeSuccessTimer = null;
  483. }
  484. // If the 100% upload progress hasn't been called then call it now
  485. if (!file.finalUploadProgress) {
  486. file.finalUploadProgress = true;
  487. this.Debug("Event: uploadProgress (simulated 100%): File ID: " + file.id + ". Bytes: " + file.file_reference.size + ". Total: " + file.file_reference.size);
  488. ExternalCall.UploadProgress(this.uploadProgress_Callback, file.ToJavaScriptObject(), file.file_reference.size, file.file_reference.size);
  489. }
  490. this.successful_uploads++;
  491. file.file_status = FileItem.FILE_STATUS_SUCCESS;
  492. this.Debug("Event: uploadSuccess: File ID: " + file.id + " Response Received: " + responseReceived.toString() + " Data: " + serverData);
  493. ExternalCall.UploadSuccess(this.uploadSuccess_Callback, file.ToJavaScriptObject(), serverData, responseReceived);
  494. this.UploadComplete(false);
  495. }
  496. private function HTTPError_Handler(event:HTTPStatusEvent):void {
  497. var isSuccessStatus:Boolean = false;
  498. for (var i:Number = 0; i < this.httpSuccess.length; i++) {
  499. if (this.httpSuccess[i] === event.status) {
  500. isSuccessStatus = true;
  501. break;
  502. }
  503. }
  504. if (isSuccessStatus) {
  505. this.Debug("Event: httpError: Translating status code " + event.status + " to uploadSuccess");
  506. var serverDataEvent:DataEvent = new DataEvent(DataEvent.UPLOAD_COMPLETE_DATA, event.bubbles, event.cancelable, "");
  507. this.ServerData_Handler(serverDataEvent);
  508. } else {
  509. this.upload_errors++;
  510. this.current_file_item.file_status = FileItem.FILE_STATUS_ERROR;
  511. this.Debug("Event: uploadError: HTTP ERROR : File ID: " + this.current_file_item.id + ". HTTP Status: " + event.status + ".");
  512. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_HTTP_ERROR, this.current_file_item.ToJavaScriptObject(), event.status.toString());
  513. this.UploadComplete(true); // An IO Error is also called so we don't want to complete the upload yet.
  514. }
  515. }
  516. // Note: Flash Player does not support Uploads that require authentication. Attempting this will trigger an
  517. // IO Error or it will prompt for a username and password and may crash the browser (FireFox/Opera)
  518. private function IOError_Handler(event:IOErrorEvent):void {
  519. // Only trigger an IO Error event if we haven't already done an HTTP error
  520. if (this.current_file_item.file_status != FileItem.FILE_STATUS_ERROR) {
  521. this.upload_errors++;
  522. this.current_file_item.file_status = FileItem.FILE_STATUS_ERROR;
  523. this.Debug("Event: uploadError : IO Error : File ID: " + this.current_file_item.id + ". IO Error: " + event.text);
  524. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_IO_ERROR, this.current_file_item.ToJavaScriptObject(), event.text);
  525. }
  526. this.UploadComplete(true);
  527. }
  528. private function SecurityError_Handler(event:SecurityErrorEvent):void {
  529. this.upload_errors++;
  530. this.current_file_item.file_status = FileItem.FILE_STATUS_ERROR;
  531. this.Debug("Event: uploadError : Security Error : File Number: " + this.current_file_item.id + ". Error text: " + event.text);
  532. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_SECURITY_ERROR, this.current_file_item.ToJavaScriptObject(), event.text);
  533. this.UploadComplete(true);
  534. }
  535. private function Select_Many_Handler(event:Event):void {
  536. this.Select_Handler(this.fileBrowserMany.fileList);
  537. }
  538. private function Select_One_Handler(event:Event):void {
  539. var fileArray:Array = new Array(1);
  540. fileArray[0] = this.fileBrowserOne;
  541. this.Select_Handler(fileArray);
  542. }
  543. private function Select_Handler(file_reference_list:Array):void {
  544. this.Debug("Select Handler: Received the files selected from the dialog. Processing the file list...");
  545. var num_files_queued:Number = 0;
  546. // Determine how many queue slots are remaining (check the unlimited (0) settings, successful uploads and queued uploads)
  547. var queue_slots_remaining:Number = 0;
  548. if (this.fileUploadLimit == 0) {
  549. queue_slots_remaining = this.fileQueueLimit == 0 ? file_reference_list.length : (this.fileQueueLimit - this.queued_uploads); // If unlimited queue make the allowed size match however many files were selected.
  550. } else {
  551. var remaining_uploads:Number = this.fileUploadLimit - this.successful_uploads - this.queued_uploads;
  552. if (remaining_uploads < 0) remaining_uploads = 0;
  553. if (this.fileQueueLimit == 0 || this.fileQueueLimit >= remaining_uploads) {
  554. queue_slots_remaining = remaining_uploads;
  555. } else if (this.fileQueueLimit < remaining_uploads) {
  556. queue_slots_remaining = this.fileQueueLimit - this.queued_uploads;
  557. }
  558. }
  559. if (queue_slots_remaining < 0) queue_slots_remaining = 0;
  560. // Check if the number of files selected is greater than the number allowed to queue up.
  561. if (queue_slots_remaining < file_reference_list.length) {
  562. this.Debug("Event: fileQueueError : Selected Files (" + file_reference_list.length + ") exceeds remaining Queue size (" + queue_slots_remaining + ").");
  563. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_QUEUE_LIMIT_EXCEEDED, null, queue_slots_remaining.toString());
  564. } else {
  565. // Process each selected file
  566. for (var i:Number = 0; i < file_reference_list.length; i++) {
  567. var file_item:FileItem = new FileItem(file_reference_list[i], this.movieName, this.file_index.length);
  568. this.file_index[file_item.index] = file_item;
  569. // Verify that the file is accessible. Zero byte files and possibly other conditions can cause a file to be inaccessible.
  570. var jsFileObj:Object = file_item.ToJavaScriptObject();
  571. var is_valid_file_reference:Boolean = (jsFileObj.filestatus !== FileItem.FILE_STATUS_ERROR);
  572. if (is_valid_file_reference) {
  573. // Check the size, if it's within the limit add it to the upload list.
  574. var size_result:Number = this.CheckFileSize(file_item);
  575. var is_valid_filetype:Boolean = this.CheckFileType(file_item);
  576. if(size_result == this.SIZE_OK && is_valid_filetype) {
  577. file_item.file_status = FileItem.FILE_STATUS_QUEUED;
  578. this.file_queue.push(file_item);
  579. this.queued_uploads++;
  580. num_files_queued++;
  581. this.Debug("Event: fileQueued : File ID: " + file_item.id);
  582. ExternalCall.FileQueued(this.fileQueued_Callback, file_item.ToJavaScriptObject());
  583. }
  584. else if (!is_valid_filetype) {
  585. //file_item.file_reference = null; // Cleanup the object
  586. file_item.file_status = FileItem.FILE_STATUS_ERROR;
  587. this.queue_errors++;
  588. this.Debug("Event: fileQueueError : File not of a valid type.");
  589. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_INVALID_FILETYPE, file_item.ToJavaScriptObject(), "File is not an allowed file type.");
  590. }
  591. else if (size_result == this.SIZE_TOO_BIG) {
  592. //file_item.file_reference = null; // Cleanup the object
  593. file_item.file_status = FileItem.FILE_STATUS_ERROR;
  594. this.queue_errors++;
  595. this.Debug("Event: fileQueueError : File exceeds size limit.");
  596. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_FILE_EXCEEDS_SIZE_LIMIT, file_item.ToJavaScriptObject(), "File size exceeds allowed limit.");
  597. }
  598. else if (size_result == this.SIZE_ZERO_BYTE) {
  599. file_item.file_reference = null; // Cleanup the object
  600. file_item.file_status = FileItem.FILE_STATUS_ERROR;
  601. this.queue_errors++;
  602. this.Debug("Event: fileQueueError : File is zero bytes.");
  603. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_ZERO_BYTE_FILE, file_item.ToJavaScriptObject(), "File is zero bytes and cannot be uploaded.");
  604. }
  605. } else {
  606. file_item.file_reference = null; // Cleanup the object
  607. file_item.file_status = FileItem.FILE_STATUS_ERROR;
  608. this.queue_errors++;
  609. this.Debug("Event: fileQueueError : File is zero bytes or FileReference is invalid.");
  610. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_ZERO_BYTE_FILE, file_item.ToJavaScriptObject(), "File is zero bytes or cannot be accessed and cannot be uploaded.");
  611. }
  612. }
  613. }
  614. this.Debug("Event: fileDialogComplete : Finished processing selected files. Files selected: " + file_reference_list.length + ". Files Queued: " + num_files_queued);
  615. ExternalCall.FileDialogComplete(this.fileDialogComplete_Callback, file_reference_list.length, num_files_queued, this.queued_uploads);
  616. }
  617. /* ****************************************************************
  618. Externally exposed functions
  619. ****************************************************************** */
  620. // Opens a file browser dialog that allows one file to be selected.
  621. private function SelectFile():void {
  622. this.fileBrowserOne = new FileReference();
  623. this.fileBrowserOne.addEventListener(Event.SELECT, this.Select_One_Handler);
  624. this.fileBrowserOne.addEventListener(Event.CANCEL, this.DialogCancelled_Handler);
  625. // Default file type settings
  626. var allowed_file_types:String = "*.*";
  627. var allowed_file_types_description:String = "All Files";
  628. // Get the instance settings
  629. if (this.fileTypes.length > 0) allowed_file_types = this.fileTypes;
  630. if (this.fileTypesDescription.length > 0) allowed_file_types_description = this.fileTypesDescription;
  631. this.Debug("Event: fileDialogStart : Browsing files. Single Select. Allowed file types: " + allowed_file_types);
  632. ExternalCall.Simple(this.fileDialogStart_Callback);
  633. try {
  634. this.fileBrowserOne.browse([new FileFilter(allowed_file_types_description, allowed_file_types)]);
  635. } catch (ex:Error) {
  636. this.Debug("Exception: " + ex.toString());
  637. }
  638. }
  639. // Opens a file browser dialog that allows multiple files to be selected.
  640. private function SelectFiles():void {
  641. var allowed_file_types:String = "*.*";
  642. var allowed_file_types_description:String = "All Files";
  643. if (this.fileTypes.length > 0) allowed_file_types = this.fileTypes;
  644. if (this.fileTypesDescription.length > 0) allowed_file_types_description = this.fileTypesDescription;
  645. this.Debug("Event: fileDialogStart : Browsing files. Multi Select. Allowed file types: " + allowed_file_types);
  646. ExternalCall.Simple(this.fileDialogStart_Callback);
  647. try {
  648. this.fileBrowserMany.browse([new FileFilter(allowed_file_types_description, allowed_file_types)]);
  649. } catch (ex:Error) {
  650. this.Debug("Exception: " + ex.toString());
  651. }
  652. }
  653. // Cancel the current upload and stops. Doesn't advance the upload pointer. The current file is requeued at the beginning.
  654. private function StopUpload():void {
  655. if (this.current_file_item != null) {
  656. // Cancel the upload and re-queue the FileItem
  657. this.current_file_item.file_reference.cancel();
  658. // Remove the event handlers
  659. this.removeEventListeners(this.current_file_item);
  660. this.current_file_item.upload_type = FileItem.UPLOAD_TYPE_NORMAL;
  661. this.current_file_item.file_status = FileItem.FILE_STATUS_QUEUED;
  662. this.file_queue.unshift(this.current_file_item);
  663. var js_object:Object = this.current_file_item.ToJavaScriptObject();
  664. this.current_file_item = null;
  665. this.Debug("Event: uploadError: upload stopped. File ID: " + js_object.ID);
  666. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_UPLOAD_STOPPED, js_object, "Upload Stopped");
  667. this.Debug("Event: uploadComplete. File ID: " + js_object.ID);
  668. ExternalCall.UploadComplete(this.uploadComplete_Callback, js_object);
  669. this.Debug("StopUpload(): upload stopped.");
  670. } else {
  671. this.Debug("StopUpload(): No file is currently uploading. Nothing to do.");
  672. }
  673. }
  674. /* Cancels the upload specified by file_id
  675. * If the file is currently uploading it is cancelled and the uploadComplete
  676. * event gets called.
  677. * If the file is not currently uploading then only the uploadCancelled event is fired.
  678. * */
  679. private function CancelUpload(file_id:String, triggerErrorEvent:Boolean = true):void {
  680. var file_item:FileItem = null;
  681. // Check the current file item
  682. if (this.current_file_item != null && (this.current_file_item.id == file_id || !file_id)) {
  683. this.current_file_item.file_reference.cancel();
  684. this.current_file_item.file_status = FileItem.FILE_STATUS_CANCELLED;
  685. this.current_file_item.upload_type = FileItem.UPLOAD_TYPE_NORMAL;
  686. this.upload_cancelled++;
  687. if (triggerErrorEvent) {
  688. this.Debug("Event: uploadError: File ID: " + this.current_file_item.id + ". Cancelled current upload");
  689. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_FILE_CANCELLED, this.current_file_item.ToJavaScriptObject(), "File Upload Cancelled.");
  690. } else {
  691. this.Debug("Event: cancelUpload: File ID: " + this.current_file_item.id + ". Cancelled current upload. Suppressed uploadError event.");
  692. }
  693. this.UploadComplete(false);
  694. } else if (file_id) {
  695. // Find the file in the queue
  696. var file_index:Number = this.FindIndexInFileQueue(file_id);
  697. if (file_index >= 0) {
  698. // Remove the file from the queue
  699. file_item = FileItem(this.file_queue[file_index]);
  700. file_item.file_status = FileItem.FILE_STATUS_CANCELLED;
  701. this.file_queue.splice(file_index, 1);
  702. this.queued_uploads--;
  703. this.upload_cancelled++;
  704. // Cancel the file (just for good measure) and make the callback
  705. file_item.file_reference.cancel();
  706. this.removeEventListeners(file_item);
  707. file_item.upload_type = FileItem.UPLOAD_TYPE_NORMAL;
  708. if (triggerErrorEvent) {
  709. this.Debug("Event: uploadError : " + file_item.id + ". Cancelled queued upload");
  710. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_FILE_CANCELLED, file_item.ToJavaScriptObject(), "File Cancelled");
  711. } else {
  712. this.Debug("Event: cancelUpload: File ID: " + file_item.id + ". Cancelled current upload. Suppressed uploadError event.");
  713. }
  714. // Get rid of the file object
  715. file_item = null;
  716. }
  717. } else {
  718. // Get the first file and cancel it
  719. while (this.file_queue.length > 0 && file_item == null) {
  720. // Check that File Reference is valid (if not make sure it's deleted and get the next one on the next loop)
  721. file_item = FileItem(this.file_queue.shift()); // Cast back to a FileItem
  722. if (typeof(file_item) == "undefined") {
  723. file_item = null;
  724. continue;
  725. }
  726. }
  727. if (file_item != null) {
  728. file_item.file_status = FileItem.FILE_STATUS_CANCELLED;
  729. this.queued_uploads--;
  730. this.upload_cancelled++;
  731. // Cancel the file (just for good measure) and make the callback
  732. file_item.file_reference.cancel();
  733. this.removeEventListeners(file_item);
  734. file_item.upload_type = FileItem.UPLOAD_TYPE_NORMAL;
  735. if (triggerErrorEvent) {
  736. this.Debug("Event: uploadError : " + file_item.id + ". Cancelled queued upload");
  737. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_FILE_CANCELLED, file_item.ToJavaScriptObject(), "File Cancelled");
  738. } else {
  739. this.Debug("Event: cancelUpload: File ID: " + file_item.id + ". Cancelled current upload. Suppressed uploadError event.");
  740. }
  741. // Get rid of the file object
  742. file_item = null;
  743. }
  744. }
  745. }
  746. /* Requeues the indicated file. Returns true if successful or if the file is
  747. * already in the queue. Otherwise returns false.
  748. * */
  749. private function RequeueUpload(fileIdentifier:*):Boolean {
  750. var file:FileItem = null;
  751. if (typeof(fileIdentifier) === "number") {
  752. var fileIndex:Number = Number(fileIdentifier);
  753. if (fileIndex >= 0 && fileIndex < this.file_index.length) {
  754. file = this.file_index[fileIndex];
  755. }
  756. } else if (typeof(fileIdentifier) === "string") {
  757. file = FindFileInFileIndex(String(fileIdentifier));
  758. } else {
  759. return false;
  760. }
  761. if (file !== null && file.file_reference !== null) {
  762. if (file.file_status === FileItem.FILE_STATUS_IN_PROGRESS || file.file_status === FileItem.FILE_STATUS_NEW) {
  763. return false;
  764. } else if (file.file_status !== FileItem.FILE_STATUS_QUEUED) {
  765. file.file_status = FileItem.FILE_STATUS_QUEUED;
  766. this.file_queue.unshift(file);
  767. this.queued_uploads++;
  768. }
  769. return true;
  770. } else {
  771. return false;
  772. }
  773. }
  774. private function GetStats():Object {
  775. return {
  776. in_progress : this.current_file_item == null ? 0 : 1,
  777. files_queued : this.queued_uploads,
  778. successful_uploads : this.successful_uploads,
  779. upload_errors : this.upload_errors,
  780. upload_cancelled : this.upload_cancelled,
  781. queue_errors : this.queue_errors
  782. };
  783. }
  784. private function SetStats(stats:Object):void {
  785. this.successful_uploads = typeof(stats["successful_uploads"]) === "number" ? stats["successful_uploads"] : this.successful_uploads;
  786. this.upload_errors = typeof(stats["upload_errors"]) === "number" ? stats["upload_errors"] : this.upload_errors;
  787. this.upload_cancelled = typeof(stats["upload_cancelled"]) === "number" ? stats["upload_cancelled"] : this.upload_cancelled;
  788. this.queue_errors = typeof(stats["queue_errors"]) === "number" ? stats["queue_errors"] : this.queue_errors;
  789. }
  790. private function GetFile(file_id:String):Object {
  791. var file_index:Number = this.FindIndexInFileQueue(file_id);
  792. if (file_index >= 0) {
  793. var file:FileItem = this.file_queue[file_index];
  794. } else {
  795. if (this.current_file_item != null) {
  796. file = this.current_file_item;
  797. } else {
  798. for (var i:Number = 0; i < this.file_queue.length; i++) {
  799. file = this.file_queue[i];
  800. if (file != null) break;
  801. }
  802. }
  803. }
  804. if (file == null) {
  805. return null;
  806. } else {
  807. return file.ToJavaScriptObject();
  808. }
  809. }
  810. private function GetFileByIndex(index:Number):Object {
  811. if (index < 0 || index > this.file_index.length - 1) {
  812. return null;
  813. } else {
  814. return this.file_index[index].ToJavaScriptObject();
  815. }
  816. }
  817. private function GetFileByQueueIndex(index:Number):Object {
  818. if (index < 0 || index > this.file_queue.length - 1) {
  819. return null;
  820. } else {
  821. return this.file_queue[index].ToJavaScriptObject();
  822. }
  823. }
  824. private function AddFileParam(file_id:String, name:String, value:String):Boolean {
  825. var item:FileItem = this.FindFileInFileIndex(file_id);
  826. if (item != null) {
  827. item.AddParam(name, value);
  828. return true;
  829. }
  830. else {
  831. return false;
  832. }
  833. }
  834. private function RemoveFileParam(file_id:String, name:String):Boolean {
  835. var item:FileItem = this.FindFileInFileIndex(file_id);
  836. if (item != null) {
  837. item.RemoveParam(name);
  838. return true;
  839. }
  840. else {
  841. return false;
  842. }
  843. }
  844. private function SetUploadURL(url:String):void {
  845. if (typeof(url) !== "undefined" && url !== "") {
  846. this.uploadURL = url;
  847. }
  848. }
  849. private function SetPostParams(post_object:Object):void {
  850. if (typeof(post_object) !== "undefined" && post_object !== null) {
  851. this.uploadPostObject = post_object;
  852. }
  853. }
  854. private function SetFileTypes(types:String, description:String):void {
  855. this.fileTypes = types;
  856. this.fileTypesDescription = description;
  857. this.LoadFileExensions(this.fileTypes);
  858. }
  859. // Sets the file size limit. Accepts size values with units: 100 b, 1KB, 23Mb, 4 Gb
  860. // Parsing is not robust. "100 200 MB KB B GB" parses as "100 MB"
  861. private function SetFileSizeLimit(size:String):void {
  862. var value:Number = 0;
  863. var unit:String = "kb";
  864. // Trim the string
  865. var trimPattern:RegExp = /^\s*|\s*$/;
  866. size = size.toLowerCase();
  867. size = size.replace(trimPattern, "");
  868. // Get the value part
  869. var values:Array = size.match(/^\d+/);
  870. if (values !== null && values.length > 0) {
  871. value = parseInt(values[0]);
  872. }
  873. if (isNaN(value) || value < 0) value = 0;
  874. // Get the units part
  875. var units:Array = size.match(/(b|kb|mb|gb)/);
  876. if (units != null && units.length > 0) {
  877. unit = units[0];
  878. }
  879. // Set the multiplier for converting the unit to bytes
  880. var multiplier:Number = 1024;
  881. if (unit === "b")
  882. multiplier = 1;
  883. else if (unit === "mb")
  884. multiplier = 1048576;
  885. else if (unit === "gb")
  886. multiplier = 1073741824;
  887. this.fileSizeLimit = value * multiplier;
  888. }
  889. private function SetFileUploadLimit(file_upload_limit:Number):void {
  890. if (file_upload_limit < 0) file_upload_limit = 0;
  891. this.fileUploadLimit = file_upload_limit;
  892. }
  893. private function SetFileQueueLimit(file_queue_limit:Number):void {
  894. if (file_queue_limit < 0) file_queue_limit = 0;
  895. this.fileQueueLimit = file_queue_limit;
  896. }
  897. private function SetFilePostName(file_post_name:String):void {
  898. if (file_post_name != "") {
  899. this.filePostName = file_post_name;
  900. }
  901. }
  902. private function SetUseQueryString(use_query_string:Boolean):void {
  903. this.useQueryString = use_query_string;
  904. }
  905. private function SetRequeueOnError(requeue_on_error:Boolean):void {
  906. this.requeueOnError = requeue_on_error;
  907. }
  908. private function SetHTTPSuccess(http_status_codes:*):void {
  909. this.httpSuccess = [];
  910. if (typeof http_status_codes === "string") {
  911. var status_code_strings:Array = http_status_codes.replace(" ", "").split(",");
  912. for each (var http_status_string:String in status_code_strings)
  913. {
  914. try {
  915. this.httpSuccess.push(Number(http_status_string));
  916. } catch (ex:Object) {
  917. // Ignore errors
  918. this.Debug("Could not add HTTP Success code: " + http_status_string);
  919. }
  920. }
  921. }
  922. else if (typeof http_status_codes === "object" && typeof http_status_codes.length === "number") {
  923. for each (var http_status:* in http_status_codes)
  924. {
  925. try {
  926. this.Debug("adding: " + http_status);
  927. this.httpSuccess.push(Number(http_status));
  928. } catch (ex:Object) {
  929. this.Debug("Could not add HTTP Success code: " + http_status);
  930. }
  931. }
  932. }
  933. }
  934. private function SetAssumeSuccessTimeout(timeout_seconds:Number):void {
  935. this.assumeSuccessTimeout = timeout_seconds < 0 ? 0 : timeout_seconds;
  936. }
  937. private function SetDebugEnabled(debug_enabled:Boolean):void {
  938. this.debugEnabled = debug_enabled;
  939. }
  940. /* *************************************************************
  941. Button Handling Functions
  942. *************************************************************** */
  943. private function SetButtonImageURL(button_image_url:String):void {
  944. this.buttonImageURL = button_image_url;
  945. try {
  946. if (this.buttonImageURL !== null && this.buttonImageURL !== "") {
  947. this.buttonLoader.load(new URLRequest(this.buttonImageURL));
  948. }
  949. } catch (ex:Object) {
  950. }
  951. }
  952. private function ButtonImageLoaded(e:Event):void {
  953. this.Debug("Button Image Loaded");
  954. this.HandleStageResize(null);
  955. }
  956. private function ButtonClickHandler(e:MouseEvent):void {
  957. if (!this.buttonStateDisabled) {
  958. if (this.buttonAction === this.BUTTON_ACTION_SELECT_FILE) {
  959. this.SelectFile();
  960. }
  961. else if (this.buttonAction === this.BUTTON_ACTION_START_UPLOAD) {
  962. this.StartUpload();
  963. }
  964. else if (this.buttonAction === this.BUTTON_ACTION_NONE) {
  965. ExternalCall.Simple(this.mouseClick_Callback);
  966. }
  967. else {
  968. this.SelectFiles();
  969. }
  970. } else {
  971. ExternalCall.Simple(this.mouseClick_Callback);
  972. }
  973. }
  974. private function UpdateButtonState():void {
  975. var xOffset:Number = 0;
  976. var yOffset:Number = 0;
  977. this.buttonLoader.x = xOffset;
  978. this.buttonLoader.y = yOffset;
  979. if (this.buttonStateDisabled) {
  980. this.buttonLoader.y = (this.buttonLoader.height / 4) * -3 + yOffset;
  981. }
  982. else if (this.buttonStateMouseDown) {
  983. this.buttonLoader.y = (this.buttonLoader.height / 4) * -2 + yOffset;
  984. }
  985. else if (this.buttonStateOver) {
  986. this.buttonLoader.y = (this.buttonLoader.height / 4) * -1 + yOffset;
  987. }
  988. else {
  989. this.buttonLoader.y = -yOffset;
  990. }
  991. };
  992. private function SetButtonText(button_text:String):void {
  993. this.buttonText = button_text;
  994. this.SetButtonTextStyle(this.buttonTextStyle);
  995. }
  996. private function SetButtonTextStyle(button_text_style:String):void {
  997. this.buttonTextStyle = button_text_style;
  998. var style:StyleSheet = new StyleSheet();
  999. style.parseCSS(this.buttonTextStyle);
  1000. this.buttonTextField.styleSheet = style;
  1001. this.buttonTextField.htmlText = this.buttonText;
  1002. }
  1003. private function SetButtonTextPadding(left:Number, top:Number):void {
  1004. this.buttonTextField.x = this.buttonTextLeftPadding = left;
  1005. this.buttonTextField.y = this.buttonTextTopPadding = top;
  1006. }
  1007. private function SetButtonDisabled(disabled:Boolean):void {
  1008. this.buttonStateDisabled = disabled;
  1009. this.UpdateButtonState();
  1010. }
  1011. private function SetButtonAction(button_action:Number):void {
  1012. this.buttonAction = button_action;
  1013. }
  1014. private function SetButtonCursor(button_cursor:Number):void {
  1015. this.buttonCursor = button_cursor;
  1016. this.buttonCursorSprite.useHandCursor = (this.buttonCursor === this.BUTTON_CURSOR_HAND);
  1017. }
  1018. /* *************************************************************
  1019. File processing and handling functions
  1020. *************************************************************** */
  1021. private function StartUpload(file_id:String = ""):void {
  1022. // Only upload a file uploads are being processed.
  1023. if (this.current_file_item != null) {
  1024. this.Debug("StartUpload(): Upload already in progress. Not starting another upload.");
  1025. return;
  1026. }
  1027. this.Debug("StartUpload: " + (file_id ? "File ID: " + file_id : "First file in queue"));
  1028. // Check the upload limit
  1029. if (this.successful_uploads >= this.fileUploadLimit && this.fileUploadLimit != 0) {
  1030. this.Debug("Event: uploadError : Upload limit reached. No more files can be uploaded.");
  1031. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_