PageRenderTime 94ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/fluid-0.7/src/webapp/fluid-components/js/swfupload/swfupload.js

https://bitbucket.org/colinbdclark/infusion
JavaScript | 989 lines | 631 code | 158 blank | 200 comment | 85 complexity | 80f4b9efb0924b386541cb0349aa02c3 MD5 | raw file
Possible License(s): BSD-3-Clause, MPL-2.0-no-copyleft-exception, MIT, LGPL-2.0, GPL-2.0, LGPL-2.1
  1. /**
  2. * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
  3. *
  4. * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
  5. *
  6. * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz???n and Mammon Media and is released under the MIT License:
  7. * http://www.opensource.org/licenses/mit-license.php
  8. *
  9. * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
  10. * http://www.opensource.org/licenses/mit-license.php
  11. *
  12. */
  13. /* ******************* */
  14. /* Constructor & Init */
  15. /* ******************* */
  16. var SWFUpload;
  17. if (SWFUpload == undefined) {
  18. SWFUpload = function (settings) {
  19. this.initSWFUpload(settings);
  20. };
  21. }
  22. SWFUpload.prototype.initSWFUpload = function (settings) {
  23. try {
  24. this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
  25. this.settings = settings;
  26. this.eventQueue = [];
  27. this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
  28. this.movieElement = null;
  29. // Setup global control tracking
  30. SWFUpload.instances[this.movieName] = this;
  31. // Load the settings. Load the Flash movie.
  32. this.initSettings();
  33. this.loadFlash();
  34. this.displayDebugInfo();
  35. } catch (ex) {
  36. delete SWFUpload.instances[this.movieName];
  37. throw ex;
  38. }
  39. };
  40. /* *************** */
  41. /* Static Members */
  42. /* *************** */
  43. SWFUpload.instances = {};
  44. SWFUpload.movieCount = 0;
  45. SWFUpload.version = "2.2.0 Beta 3";
  46. SWFUpload.QUEUE_ERROR = {
  47. QUEUE_LIMIT_EXCEEDED : -100,
  48. FILE_EXCEEDS_SIZE_LIMIT : -110,
  49. ZERO_BYTE_FILE : -120,
  50. INVALID_FILETYPE : -130
  51. };
  52. SWFUpload.UPLOAD_ERROR = {
  53. HTTP_ERROR : -200,
  54. MISSING_UPLOAD_URL : -210,
  55. IO_ERROR : -220,
  56. SECURITY_ERROR : -230,
  57. UPLOAD_LIMIT_EXCEEDED : -240,
  58. UPLOAD_FAILED : -250,
  59. SPECIFIED_FILE_ID_NOT_FOUND : -260,
  60. FILE_VALIDATION_FAILED : -270,
  61. FILE_CANCELLED : -280,
  62. UPLOAD_STOPPED : -290
  63. };
  64. SWFUpload.FILE_STATUS = {
  65. QUEUED : -1,
  66. IN_PROGRESS : -2,
  67. ERROR : -3,
  68. COMPLETE : -4,
  69. CANCELLED : -5
  70. };
  71. SWFUpload.BUTTON_ACTION = {
  72. SELECT_FILE : -100,
  73. SELECT_FILES : -110,
  74. START_UPLOAD : -120
  75. };
  76. SWFUpload.CURSOR = {
  77. ARROW : -1,
  78. HAND : -2
  79. };
  80. SWFUpload.WINDOW_MODE = {
  81. WINDOW : "window",
  82. TRANSPARENT : "transparent",
  83. OPAQUE : "opaque"
  84. };
  85. /* ******************** */
  86. /* Instance Members */
  87. /* ******************** */
  88. // Private: initSettings ensures that all the
  89. // settings are set, getting a default value if one was not assigned.
  90. SWFUpload.prototype.initSettings = function () {
  91. this.ensureDefault = function (settingName, defaultValue) {
  92. this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
  93. };
  94. // Upload backend settings
  95. this.ensureDefault("upload_url", "");
  96. this.ensureDefault("file_post_name", "Filedata");
  97. this.ensureDefault("post_params", {});
  98. this.ensureDefault("use_query_string", false);
  99. this.ensureDefault("requeue_on_error", false);
  100. this.ensureDefault("http_success", []);
  101. // File Settings
  102. this.ensureDefault("file_types", "*.*");
  103. this.ensureDefault("file_types_description", "All Files");
  104. this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
  105. this.ensureDefault("file_upload_limit", 0);
  106. this.ensureDefault("file_queue_limit", 0);
  107. // Flash Settings
  108. this.ensureDefault("flash_url", "swfupload_f10.swf");
  109. this.ensureDefault("prevent_swf_caching", true);
  110. // Button Settings
  111. this.ensureDefault("button_image_url", "");
  112. this.ensureDefault("button_width", 1);
  113. this.ensureDefault("button_height", 1);
  114. this.ensureDefault("button_text", "");
  115. this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
  116. this.ensureDefault("button_text_top_padding", 0);
  117. this.ensureDefault("button_text_left_padding", 0);
  118. this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
  119. this.ensureDefault("button_disabled", false);
  120. this.ensureDefault("button_placeholder_id", null);
  121. this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
  122. this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
  123. // Debug Settings
  124. this.ensureDefault("debug", false);
  125. this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
  126. // Event Handlers
  127. this.settings.return_upload_start_handler = this.returnUploadStart;
  128. this.ensureDefault("swfupload_loaded_handler", null);
  129. this.ensureDefault("file_dialog_start_handler", null);
  130. this.ensureDefault("file_queued_handler", null);
  131. this.ensureDefault("file_queue_error_handler", null);
  132. this.ensureDefault("file_dialog_complete_handler", null);
  133. this.ensureDefault("upload_start_handler", null);
  134. this.ensureDefault("upload_progress_handler", null);
  135. this.ensureDefault("upload_error_handler", null);
  136. this.ensureDefault("upload_success_handler", null);
  137. this.ensureDefault("upload_complete_handler", null);
  138. this.ensureDefault("debug_handler", this.debugMessage);
  139. this.ensureDefault("custom_settings", {});
  140. // Other settings
  141. this.customSettings = this.settings.custom_settings;
  142. // Update the flash url if needed
  143. if (this.settings.prevent_swf_caching) {
  144. this.settings.flash_url = this.settings.flash_url + "?swfuploadrnd=" + Math.floor(Math.random() * 999999999);
  145. }
  146. delete this.ensureDefault;
  147. };
  148. SWFUpload.prototype.loadFlash = function () {
  149. if (this.settings.button_placeholder_id !== "") {
  150. this.replaceWithFlash();
  151. } else {
  152. this.appendFlash();
  153. }
  154. };
  155. // Private: appendFlash gets the HTML tag for the Flash
  156. // It then appends the flash to the body
  157. SWFUpload.prototype.appendFlash = function () {
  158. var targetElement, container;
  159. // Make sure an element with the ID we are going to use doesn't already exist
  160. if (document.getElementById(this.movieName) !== null) {
  161. throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
  162. }
  163. // Get the body tag where we will be adding the flash movie
  164. targetElement = document.getElementsByTagName("body")[0];
  165. if (targetElement == undefined) {
  166. throw "Could not find the 'body' element.";
  167. }
  168. // Append the container and load the flash
  169. container = document.createElement("div");
  170. container.style.width = "1px";
  171. container.style.height = "1px";
  172. container.style.overflow = "hidden";
  173. targetElement.appendChild(container);
  174. container.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
  175. // Fix IE Flash/Form bug
  176. if (window[this.movieName] == undefined) {
  177. window[this.movieName] = this.getMovieElement();
  178. }
  179. };
  180. // Private: replaceWithFlash replaces the button_placeholder element with the flash movie.
  181. SWFUpload.prototype.replaceWithFlash = function () {
  182. var targetElement, tempParent;
  183. // Make sure an element with the ID we are going to use doesn't already exist
  184. if (document.getElementById(this.movieName) !== null) {
  185. throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
  186. }
  187. // Get the element where we will be placing the flash movie
  188. targetElement = document.getElementById(this.settings.button_placeholder_id);
  189. if (targetElement == undefined) {
  190. throw "Could not find the placeholder element.";
  191. }
  192. // Append the container and load the flash
  193. tempParent = document.createElement("div");
  194. tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
  195. targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
  196. // Fix IE Flash/Form bug
  197. if (window[this.movieName] == undefined) {
  198. window[this.movieName] = this.getMovieElement();
  199. }
  200. };
  201. // Private: getFlashHTML generates the object tag needed to embed the flash in to the document
  202. SWFUpload.prototype.getFlashHTML = function () {
  203. // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
  204. return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
  205. '<param name="wmode" value="', this.settings.button_window_mode , '" />',
  206. '<param name="movie" value="', this.settings.flash_url, '" />',
  207. '<param name="quality" value="high" />',
  208. '<param name="menu" value="false" />',
  209. '<param name="allowScriptAccess" value="always" />',
  210. '<param name="flashvars" value="' + this.getFlashVars() + '" />',
  211. '</object>'].join("");
  212. };
  213. // Private: getFlashVars builds the parameter string that will be passed
  214. // to flash in the flashvars param.
  215. SWFUpload.prototype.getFlashVars = function () {
  216. // Build a string from the post param object
  217. var paramString = this.buildParamString();
  218. var httpSuccessString = this.settings.http_success.join(",");
  219. // Build the parameter string
  220. return ["movieName=", encodeURIComponent(this.movieName),
  221. "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
  222. "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
  223. "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
  224. "&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
  225. "&amp;params=", encodeURIComponent(paramString),
  226. "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
  227. "&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
  228. "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
  229. "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
  230. "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
  231. "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
  232. "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
  233. "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
  234. "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
  235. "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
  236. "&amp;buttonText=", encodeURIComponent(this.settings.button_text),
  237. "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
  238. "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
  239. "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
  240. "&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
  241. "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
  242. "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
  243. ].join("");
  244. };
  245. // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
  246. // The element is cached after the first lookup
  247. SWFUpload.prototype.getMovieElement = function () {
  248. if (this.movieElement == undefined) {
  249. this.movieElement = document.getElementById(this.movieName);
  250. }
  251. if (this.movieElement === null) {
  252. throw "Could not find Flash element";
  253. }
  254. return this.movieElement;
  255. };
  256. // Private: buildParamString takes the name/value pairs in the post_params setting object
  257. // and joins them up in to a string formatted "name=value&amp;name=value"
  258. SWFUpload.prototype.buildParamString = function () {
  259. var postParams = this.settings.post_params;
  260. var paramStringPairs = [];
  261. if (typeof(postParams) === "object") {
  262. for (var name in postParams) {
  263. if (postParams.hasOwnProperty(name)) {
  264. paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
  265. }
  266. }
  267. }
  268. return paramStringPairs.join("&amp;");
  269. };
  270. // Public: Used to remove a SWFUpload instance from the page. This method strives to remove
  271. // all references to the SWF, and other objects so memory is properly freed.
  272. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
  273. // Credits: Major improvements provided by steffen
  274. SWFUpload.prototype.destroy = function () {
  275. try {
  276. // Make sure Flash is done before we try to remove it
  277. this.cancelUpload(null, false);
  278. // Remove the SWFUpload DOM nodes
  279. var movieElement = null;
  280. movieElement = this.getMovieElement();
  281. if (movieElement) {
  282. // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
  283. for (var i in movieElement) {
  284. try {
  285. if (typeof(movieElement[i]) === "function") {
  286. movieElement[i] = null;
  287. }
  288. } catch (ex1) {}
  289. }
  290. // Remove the Movie Element from the page
  291. try {
  292. movieElement.parentNode.removeChild(movieElement);
  293. } catch (ex) {}
  294. }
  295. // Remove IE form fix reference
  296. window[this.movieName] = null;
  297. // Destroy other references
  298. SWFUpload.instances[this.movieName] = null;
  299. delete SWFUpload.instances[this.movieName];
  300. this.movieElement = null;
  301. this.settings = null;
  302. this.customSettings = null;
  303. this.eventQueue = null;
  304. this.movieName = null;
  305. return true;
  306. } catch (ex1) {
  307. return false;
  308. }
  309. };
  310. // Public: displayDebugInfo prints out settings and configuration
  311. // information about this SWFUpload instance.
  312. // This function (and any references to it) can be deleted when placing
  313. // SWFUpload in production.
  314. SWFUpload.prototype.displayDebugInfo = function () {
  315. this.debug(
  316. [
  317. "---SWFUpload Instance Info---\n",
  318. "Version: ", SWFUpload.version, "\n",
  319. "Movie Name: ", this.movieName, "\n",
  320. "Settings:\n",
  321. "\t", "upload_url: ", this.settings.upload_url, "\n",
  322. "\t", "flash_url: ", this.settings.flash_url, "\n",
  323. "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
  324. "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
  325. "\t", "http_success: ", this.settings.http_success.join(", "), "\n",
  326. "\t", "file_post_name: ", this.settings.file_post_name, "\n",
  327. "\t", "post_params: ", this.settings.post_params.toString(), "\n",
  328. "\t", "file_types: ", this.settings.file_types, "\n",
  329. "\t", "file_types_description: ", this.settings.file_types_description, "\n",
  330. "\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
  331. "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
  332. "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
  333. "\t", "debug: ", this.settings.debug.toString(), "\n",
  334. "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
  335. "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
  336. "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
  337. "\t", "button_width: ", this.settings.button_width.toString(), "\n",
  338. "\t", "button_height: ", this.settings.button_height.toString(), "\n",
  339. "\t", "button_text: ", this.settings.button_text.toString(), "\n",
  340. "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
  341. "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
  342. "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
  343. "\t", "button_action: ", this.settings.button_action.toString(), "\n",
  344. "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
  345. "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
  346. "Event Handlers:\n",
  347. "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
  348. "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
  349. "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
  350. "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
  351. "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
  352. "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
  353. "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
  354. "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
  355. "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
  356. "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n"
  357. ].join("")
  358. );
  359. };
  360. /* Note: addSetting and getSetting are no longer used by SWFUpload but are included
  361. the maintain v2 API compatibility
  362. */
  363. // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
  364. SWFUpload.prototype.addSetting = function (name, value, default_value) {
  365. if (value == undefined) {
  366. return (this.settings[name] = default_value);
  367. } else {
  368. return (this.settings[name] = value);
  369. }
  370. };
  371. // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
  372. SWFUpload.prototype.getSetting = function (name) {
  373. if (this.settings[name] != undefined) {
  374. return this.settings[name];
  375. }
  376. return "";
  377. };
  378. // Private: callFlash handles function calls made to the Flash element.
  379. // Calls are made with a setTimeout for some functions to work around
  380. // bugs in the ExternalInterface library.
  381. SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
  382. argumentArray = argumentArray || [];
  383. var movieElement = this.getMovieElement();
  384. var returnValue, returnString;
  385. // Flash's method if calling ExternalInterface methods (code adapted from MooTools).
  386. try {
  387. returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
  388. returnValue = eval(returnString);
  389. } catch (ex) {
  390. throw "Call to " + functionName + " failed";
  391. }
  392. // Unescape file post param values
  393. if (returnValue != undefined && typeof returnValue.post === "object") {
  394. returnValue = this.unescapeFilePostParams(returnValue);
  395. }
  396. return returnValue;
  397. };
  398. /**
  399. * Version of callFlash that is compatible with Flash 9.
  400. */
  401. SWFUpload.callFlash_Flash9Compatibility = function (functionName, argumentArray) {
  402. argumentArray = argumentArray || [];
  403. var self = this;
  404. var callFunction = function () {
  405. var movieElement = self.getMovieElement();
  406. var returnValue;
  407. if (typeof(movieElement[functionName]) === "function") {
  408. // We have to go through all this if/else stuff because the Flash functions don't have apply() and only accept the exact number of arguments.
  409. if (argumentArray.length === 0) {
  410. returnValue = movieElement[functionName]();
  411. } else if (argumentArray.length === 1) {
  412. returnValue = movieElement[functionName](argumentArray[0]);
  413. } else if (argumentArray.length === 2) {
  414. returnValue = movieElement[functionName](argumentArray[0], argumentArray[1]);
  415. } else if (argumentArray.length === 3) {
  416. returnValue = movieElement[functionName](argumentArray[0], argumentArray[1], argumentArray[2]);
  417. } else {
  418. throw "Too many arguments";
  419. }
  420. // Unescape file post param values
  421. if (returnValue != undefined && typeof(returnValue.post) === "object") {
  422. returnValue = self.unescapeFilePostParams(returnValue);
  423. }
  424. return returnValue;
  425. } else {
  426. throw "Invalid function name";
  427. }
  428. };
  429. return callFunction();
  430. };
  431. /* *****************************
  432. -- Flash control methods --
  433. Your UI should use these
  434. to operate SWFUpload
  435. ***************************** */
  436. // WARNING: this function does not work in Flash Player 10
  437. // Public: selectFile causes a File Selection Dialog window to appear. This
  438. // dialog only allows 1 file to be selected.
  439. SWFUpload.prototype.selectFile = function () {
  440. this.callFlash("SelectFile");
  441. };
  442. // WARNING: this function does not work in Flash Player 10
  443. // Public: selectFiles causes a File Selection Dialog window to appear/ This
  444. // dialog allows the user to select any number of files
  445. // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
  446. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around
  447. // for this bug.
  448. SWFUpload.prototype.selectFiles = function () {
  449. this.callFlash("SelectFiles");
  450. };
  451. // Public: startUpload starts uploading the first file in the queue unless
  452. // the optional parameter 'fileID' specifies the ID
  453. SWFUpload.prototype.startUpload = function (fileID) {
  454. this.callFlash("StartUpload", [fileID]);
  455. };
  456. // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index.
  457. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
  458. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
  459. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
  460. // This section has been commented out, and we've removed the passing of triggerErrorEvent to the Flash side,
  461. // because of FLUID-1982. We use a patched version of swfupload.js (this file) which is intended to work with
  462. // the Flash movies from both SWFUpload 2.1.0 and 2.2.0b3.
  463. // The 2.1.0 version of the movie doesn't expect this second argument and will throw an error.
  464. // For more details, see http://issues.fluidproject.org/browse/FLUID-1982.
  465. //if (triggerErrorEvent !== false) {
  466. // triggerErrorEvent = true;
  467. //}
  468. this.callFlash("CancelUpload", [fileID]);
  469. };
  470. // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
  471. // If nothing is currently uploading then nothing happens.
  472. SWFUpload.prototype.stopUpload = function () {
  473. this.callFlash("StopUpload");
  474. };
  475. /* ************************
  476. * Settings methods
  477. * These methods change the SWFUpload settings.
  478. * SWFUpload settings should not be changed directly on the settings object
  479. * since many of the settings need to be passed to Flash in order to take
  480. * effect.
  481. * *********************** */
  482. // Public: getStats gets the file statistics object.
  483. SWFUpload.prototype.getStats = function () {
  484. return this.callFlash("GetStats");
  485. };
  486. // Public: setStats changes the SWFUpload statistics. You shouldn't need to
  487. // change the statistics but you can. Changing the statistics does not
  488. // affect SWFUpload accept for the successful_uploads count which is used
  489. // by the upload_limit setting to determine how many files the user may upload.
  490. SWFUpload.prototype.setStats = function (statsObject) {
  491. this.callFlash("SetStats", [statsObject]);
  492. };
  493. // Public: getFile retrieves a File object by ID or Index. If the file is
  494. // not found then 'null' is returned.
  495. SWFUpload.prototype.getFile = function (fileID) {
  496. if (typeof(fileID) === "number") {
  497. return this.callFlash("GetFileByIndex", [fileID]);
  498. } else {
  499. return this.callFlash("GetFile", [fileID]);
  500. }
  501. };
  502. // Public: addFileParam sets a name/value pair that will be posted with the
  503. // file specified by the Files ID. If the name already exists then the
  504. // exiting value will be overwritten.
  505. SWFUpload.prototype.addFileParam = function (fileID, name, value) {
  506. return this.callFlash("AddFileParam", [fileID, name, value]);
  507. };
  508. // Public: removeFileParam removes a previously set (by addFileParam) name/value
  509. // pair from the specified file.
  510. SWFUpload.prototype.removeFileParam = function (fileID, name) {
  511. this.callFlash("RemoveFileParam", [fileID, name]);
  512. };
  513. // Public: setUploadUrl changes the upload_url setting.
  514. SWFUpload.prototype.setUploadURL = function (url) {
  515. this.settings.upload_url = url.toString();
  516. this.callFlash("SetUploadURL", [url]);
  517. };
  518. // Public: setPostParams changes the post_params setting
  519. SWFUpload.prototype.setPostParams = function (paramsObject) {
  520. this.settings.post_params = paramsObject;
  521. this.callFlash("SetPostParams", [paramsObject]);
  522. };
  523. // Public: addPostParam adds post name/value pair. Each name can have only one value.
  524. SWFUpload.prototype.addPostParam = function (name, value) {
  525. this.settings.post_params[name] = value;
  526. this.callFlash("SetPostParams", [this.settings.post_params]);
  527. };
  528. // Public: removePostParam deletes post name/value pair.
  529. SWFUpload.prototype.removePostParam = function (name) {
  530. delete this.settings.post_params[name];
  531. this.callFlash("SetPostParams", [this.settings.post_params]);
  532. };
  533. // Public: setFileTypes changes the file_types setting and the file_types_description setting
  534. SWFUpload.prototype.setFileTypes = function (types, description) {
  535. this.settings.file_types = types;
  536. this.settings.file_types_description = description;
  537. this.callFlash("SetFileTypes", [types, description]);
  538. };
  539. // Public: setFileSizeLimit changes the file_size_limit setting
  540. SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
  541. this.settings.file_size_limit = fileSizeLimit;
  542. this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
  543. };
  544. // Public: setFileUploadLimit changes the file_upload_limit setting
  545. SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
  546. this.settings.file_upload_limit = fileUploadLimit;
  547. this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
  548. };
  549. // Public: setFileQueueLimit changes the file_queue_limit setting
  550. SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
  551. this.settings.file_queue_limit = fileQueueLimit;
  552. this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
  553. };
  554. // Public: setFilePostName changes the file_post_name setting
  555. SWFUpload.prototype.setFilePostName = function (filePostName) {
  556. this.settings.file_post_name = filePostName;
  557. this.callFlash("SetFilePostName", [filePostName]);
  558. };
  559. // Public: setUseQueryString changes the use_query_string setting
  560. SWFUpload.prototype.setUseQueryString = function (useQueryString) {
  561. this.settings.use_query_string = useQueryString;
  562. this.callFlash("SetUseQueryString", [useQueryString]);
  563. };
  564. // Public: setRequeueOnError changes the requeue_on_error setting
  565. SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
  566. this.settings.requeue_on_error = requeueOnError;
  567. this.callFlash("SetRequeueOnError", [requeueOnError]);
  568. };
  569. // Public: setHTTPSuccess changes the http_success setting
  570. SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
  571. if (typeof http_status_codes === "string") {
  572. http_status_codes = http_status_codes.replace(" ", "").split(",");
  573. }
  574. this.settings.http_success = http_status_codes;
  575. this.callFlash("SetHTTPSuccess", [http_status_codes]);
  576. };
  577. // Public: setDebugEnabled changes the debug_enabled setting
  578. SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
  579. this.settings.debug_enabled = debugEnabled;
  580. this.callFlash("SetDebugEnabled", [debugEnabled]);
  581. };
  582. // Public: setButtonImageURL loads a button image sprite
  583. SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
  584. if (buttonImageURL == undefined) {
  585. buttonImageURL = "";
  586. }
  587. this.settings.button_image_url = buttonImageURL;
  588. this.callFlash("SetButtonImageURL", [buttonImageURL]);
  589. };
  590. // Public: setButtonDimensions resizes the Flash Movie and button
  591. SWFUpload.prototype.setButtonDimensions = function (width, height) {
  592. this.settings.button_width = width;
  593. this.settings.button_height = height;
  594. var movie = this.getMovieElement();
  595. if (movie != undefined) {
  596. movie.style.width = width + "px";
  597. movie.style.height = height + "px";
  598. }
  599. this.callFlash("SetButtonDimensions", [width, height]);
  600. };
  601. // Public: setButtonText Changes the text overlaid on the button
  602. SWFUpload.prototype.setButtonText = function (html) {
  603. this.settings.button_text = html;
  604. this.callFlash("SetButtonText", [html]);
  605. };
  606. // Public: setButtonTextPadding changes the top and left padding of the text overlay
  607. SWFUpload.prototype.setButtonTextPadding = function (left, top) {
  608. this.settings.button_text_top_padding = top;
  609. this.settings.button_text_left_padding = left;
  610. this.callFlash("SetButtonTextPadding", [left, top]);
  611. };
  612. // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
  613. SWFUpload.prototype.setButtonTextStyle = function (css) {
  614. this.settings.button_text_style = css;
  615. this.callFlash("SetButtonTextStyle", [css]);
  616. };
  617. // Public: setButtonDisabled disables/enables the button
  618. SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
  619. this.settings.button_disabled = isDisabled;
  620. this.callFlash("SetButtonDisabled", [isDisabled]);
  621. };
  622. // Public: setButtonAction sets the action that occurs when the button is clicked
  623. SWFUpload.prototype.setButtonAction = function (buttonAction) {
  624. this.settings.button_action = buttonAction;
  625. this.callFlash("SetButtonAction", [buttonAction]);
  626. };
  627. // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
  628. SWFUpload.prototype.setButtonCursor = function (cursor) {
  629. this.settings.button_cursor = cursor;
  630. this.callFlash("SetButtonCursor", [cursor]);
  631. };
  632. /* *******************************
  633. Flash Event Interfaces
  634. These functions are used by Flash to trigger the various
  635. events.
  636. All these functions a Private.
  637. Because the ExternalInterface library is buggy the event calls
  638. are added to a queue and the queue then executed by a setTimeout.
  639. This ensures that events are executed in a determinate order and that
  640. the ExternalInterface bugs are avoided.
  641. ******************************* */
  642. SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
  643. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  644. if (argumentArray == undefined) {
  645. argumentArray = [];
  646. } else if (!(argumentArray instanceof Array)) {
  647. argumentArray = [argumentArray];
  648. }
  649. var self = this;
  650. if (typeof this.settings[handlerName] === "function") {
  651. // Queue the event
  652. this.eventQueue.push(function () {
  653. this.settings[handlerName].apply(this, argumentArray);
  654. });
  655. // Execute the next queued event
  656. setTimeout(function () {
  657. self.executeNextEvent();
  658. }, 0);
  659. } else if (this.settings[handlerName] !== null) {
  660. throw "Event handler " + handlerName + " is unknown or is not a function";
  661. }
  662. };
  663. // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
  664. // we must queue them in order to garentee that they are executed in order.
  665. SWFUpload.prototype.executeNextEvent = function () {
  666. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  667. var f = this.eventQueue ? this.eventQueue.shift() : null;
  668. if (typeof(f) === "function") {
  669. f.apply(this);
  670. }
  671. };
  672. // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
  673. // properties that contain characters that are not valid for JavaScript identifiers. To work around this
  674. // the Flash Component escapes the parameter names and we must unescape again before passing them along.
  675. SWFUpload.prototype.unescapeFilePostParams = function (file) {
  676. var reg = /[$]([0-9a-f]{4})/i;
  677. var unescapedPost = {};
  678. var uk;
  679. if (file != undefined) {
  680. for (var k in file.post) {
  681. if (file.post.hasOwnProperty(k)) {
  682. uk = k;
  683. var match;
  684. while ((match = reg.exec(uk)) !== null) {
  685. uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
  686. }
  687. unescapedPost[uk] = file.post[k];
  688. }
  689. }
  690. file.post = unescapedPost;
  691. }
  692. return file;
  693. };
  694. SWFUpload.prototype.flashReady = function () {
  695. // Check that the movie element is loaded correctly with its ExternalInterface methods defined
  696. var movieElement = this.getMovieElement();
  697. // Pro-actively unhook all the Flash functions
  698. if (typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  699. this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
  700. for (var key in movieElement) {
  701. try {
  702. if (typeof(movieElement[key]) === "function") {
  703. movieElement[key] = null;
  704. }
  705. } catch (ex) {
  706. }
  707. }
  708. }
  709. this.queueEvent("swfupload_loaded_handler");
  710. };
  711. /* This is a chance to do something before the browse window opens */
  712. SWFUpload.prototype.fileDialogStart = function () {
  713. this.queueEvent("file_dialog_start_handler");
  714. };
  715. /* Called when a file is successfully added to the queue. */
  716. SWFUpload.prototype.fileQueued = function (file) {
  717. file = this.unescapeFilePostParams(file);
  718. this.queueEvent("file_queued_handler", file);
  719. };
  720. /* Handle errors that occur when an attempt to queue a file fails. */
  721. SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
  722. file = this.unescapeFilePostParams(file);
  723. this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
  724. };
  725. /* Called after the file dialog has closed and the selected files have been queued.
  726. You could call startUpload here if you want the queued files to begin uploading immediately. */
  727. SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued) {
  728. this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued]);
  729. };
  730. SWFUpload.prototype.uploadStart = function (file) {
  731. file = this.unescapeFilePostParams(file);
  732. this.queueEvent("return_upload_start_handler", file);
  733. };
  734. SWFUpload.prototype.returnUploadStart = function (file) {
  735. var returnValue;
  736. if (typeof this.settings.upload_start_handler === "function") {
  737. file = this.unescapeFilePostParams(file);
  738. returnValue = this.settings.upload_start_handler.call(this, file);
  739. } else if (this.settings.upload_start_handler != undefined) {
  740. throw "upload_start_handler must be a function";
  741. }
  742. // Convert undefined to true so if nothing is returned from the upload_start_handler it is
  743. // interpretted as 'true'.
  744. if (returnValue === undefined) {
  745. returnValue = true;
  746. }
  747. returnValue = !!returnValue;
  748. this.callFlash("ReturnUploadStart", [returnValue]);
  749. };
  750. SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
  751. file = this.unescapeFilePostParams(file);
  752. this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
  753. };
  754. SWFUpload.prototype.uploadError = function (file, errorCode, message) {
  755. file = this.unescapeFilePostParams(file);
  756. this.queueEvent("upload_error_handler", [file, errorCode, message]);
  757. };
  758. SWFUpload.prototype.uploadSuccess = function (file, serverData) {
  759. file = this.unescapeFilePostParams(file);
  760. this.queueEvent("upload_success_handler", [file, serverData]);
  761. };
  762. SWFUpload.prototype.uploadComplete = function (file) {
  763. file = this.unescapeFilePostParams(file);
  764. this.queueEvent("upload_complete_handler", file);
  765. };
  766. /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
  767. internal debug console. You can override this event and have messages written where you want. */
  768. SWFUpload.prototype.debug = function (message) {
  769. this.queueEvent("debug_handler", message);
  770. };
  771. /* **********************************
  772. Debug Console
  773. The debug console is a self contained, in page location
  774. for debug message to be sent. The Debug Console adds
  775. itself to the body if necessary.
  776. The console is automatically scrolled as messages appear.
  777. If you are using your own debug handler or when you deploy to production and
  778. have debug disabled you can remove these functions to reduce the file size
  779. and complexity.
  780. ********************************** */
  781. // Private: debugMessage is the default debug_handler. If you want to print debug messages
  782. // call the debug() function. When overriding the function your own function should
  783. // check to see if the debug setting is true before outputting debug information.
  784. SWFUpload.prototype.debugMessage = function (message) {
  785. if (this.settings.debug) {
  786. var exceptionMessage, exceptionValues = [];
  787. // Check for an exception object and print it nicely
  788. if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
  789. for (var key in message) {
  790. if (message.hasOwnProperty(key)) {
  791. exceptionValues.push(key + ": " + message[key]);
  792. }
  793. }
  794. exceptionMessage = exceptionValues.join("\n") || "";
  795. exceptionValues = exceptionMessage.split("\n");
  796. exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
  797. SWFUpload.Console.writeLine(exceptionMessage);
  798. } else {
  799. SWFUpload.Console.writeLine(message);
  800. }
  801. }
  802. };
  803. SWFUpload.Console = {};
  804. SWFUpload.Console.writeLine = function (message) {
  805. var console, documentForm;
  806. try {
  807. console = document.getElementById("SWFUpload_Console");
  808. if (!console) {
  809. documentForm = document.createElement("form");
  810. document.getElementsByTagName("body")[0].appendChild(documentForm);
  811. console = document.createElement("textarea");
  812. console.id = "SWFUpload_Console";
  813. console.style.fontFamily = "monospace";
  814. console.setAttribute("wrap", "off");
  815. console.wrap = "off";
  816. console.style.overflow = "auto";
  817. console.style.width = "700px";
  818. console.style.height = "350px";
  819. console.style.margin = "5px";
  820. documentForm.appendChild(console);
  821. }
  822. console.value += message + "\n";
  823. console.scrollTop = console.scrollHeight - console.clientHeight;
  824. } catch (ex) {
  825. alert("Exception: " + ex.name + " Message: " + ex.message);
  826. }
  827. };