PageRenderTime 64ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/colinbdclark/infusion
JavaScript | 983 lines | 634 code | 157 blank | 192 comment | 86 complexity | e30f292fe04380790d4b7a0b13dd8392 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. if (triggerErrorEvent !== false) {
  461. triggerErrorEvent = true;
  462. }
  463. this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
  464. };
  465. // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
  466. // If nothing is currently uploading then nothing happens.
  467. SWFUpload.prototype.stopUpload = function () {
  468. this.callFlash("StopUpload");
  469. };
  470. /* ************************
  471. * Settings methods
  472. * These methods change the SWFUpload settings.
  473. * SWFUpload settings should not be changed directly on the settings object
  474. * since many of the settings need to be passed to Flash in order to take
  475. * effect.
  476. * *********************** */
  477. // Public: getStats gets the file statistics object.
  478. SWFUpload.prototype.getStats = function () {
  479. return this.callFlash("GetStats");
  480. };
  481. // Public: setStats changes the SWFUpload statistics. You shouldn't need to
  482. // change the statistics but you can. Changing the statistics does not
  483. // affect SWFUpload accept for the successful_uploads count which is used
  484. // by the upload_limit setting to determine how many files the user may upload.
  485. SWFUpload.prototype.setStats = function (statsObject) {
  486. this.callFlash("SetStats", [statsObject]);
  487. };
  488. // Public: getFile retrieves a File object by ID or Index. If the file is
  489. // not found then 'null' is returned.
  490. SWFUpload.prototype.getFile = function (fileID) {
  491. if (typeof(fileID) === "number") {
  492. return this.callFlash("GetFileByIndex", [fileID]);
  493. } else {
  494. return this.callFlash("GetFile", [fileID]);
  495. }
  496. };
  497. // Public: addFileParam sets a name/value pair that will be posted with the
  498. // file specified by the Files ID. If the name already exists then the
  499. // exiting value will be overwritten.
  500. SWFUpload.prototype.addFileParam = function (fileID, name, value) {
  501. return this.callFlash("AddFileParam", [fileID, name, value]);
  502. };
  503. // Public: removeFileParam removes a previously set (by addFileParam) name/value
  504. // pair from the specified file.
  505. SWFUpload.prototype.removeFileParam = function (fileID, name) {
  506. this.callFlash("RemoveFileParam", [fileID, name]);
  507. };
  508. // Public: setUploadUrl changes the upload_url setting.
  509. SWFUpload.prototype.setUploadURL = function (url) {
  510. this.settings.upload_url = url.toString();
  511. this.callFlash("SetUploadURL", [url]);
  512. };
  513. // Public: setPostParams changes the post_params setting
  514. SWFUpload.prototype.setPostParams = function (paramsObject) {
  515. this.settings.post_params = paramsObject;
  516. this.callFlash("SetPostParams", [paramsObject]);
  517. };
  518. // Public: addPostParam adds post name/value pair. Each name can have only one value.
  519. SWFUpload.prototype.addPostParam = function (name, value) {
  520. this.settings.post_params[name] = value;
  521. this.callFlash("SetPostParams", [this.settings.post_params]);
  522. };
  523. // Public: removePostParam deletes post name/value pair.
  524. SWFUpload.prototype.removePostParam = function (name) {
  525. delete this.settings.post_params[name];
  526. this.callFlash("SetPostParams", [this.settings.post_params]);
  527. };
  528. // Public: setFileTypes changes the file_types setting and the file_types_description setting
  529. SWFUpload.prototype.setFileTypes = function (types, description) {
  530. this.settings.file_types = types;
  531. this.settings.file_types_description = description;
  532. this.callFlash("SetFileTypes", [types, description]);
  533. };
  534. // Public: setFileSizeLimit changes the file_size_limit setting
  535. SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
  536. this.settings.file_size_limit = fileSizeLimit;
  537. this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
  538. };
  539. // Public: setFileUploadLimit changes the file_upload_limit setting
  540. SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
  541. this.settings.file_upload_limit = fileUploadLimit;
  542. this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
  543. };
  544. // Public: setFileQueueLimit changes the file_queue_limit setting
  545. SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
  546. this.settings.file_queue_limit = fileQueueLimit;
  547. this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
  548. };
  549. // Public: setFilePostName changes the file_post_name setting
  550. SWFUpload.prototype.setFilePostName = function (filePostName) {
  551. this.settings.file_post_name = filePostName;
  552. this.callFlash("SetFilePostName", [filePostName]);
  553. };
  554. // Public: setUseQueryString changes the use_query_string setting
  555. SWFUpload.prototype.setUseQueryString = function (useQueryString) {
  556. this.settings.use_query_string = useQueryString;
  557. this.callFlash("SetUseQueryString", [useQueryString]);
  558. };
  559. // Public: setRequeueOnError changes the requeue_on_error setting
  560. SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
  561. this.settings.requeue_on_error = requeueOnError;
  562. this.callFlash("SetRequeueOnError", [requeueOnError]);
  563. };
  564. // Public: setHTTPSuccess changes the http_success setting
  565. SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
  566. if (typeof http_status_codes === "string") {
  567. http_status_codes = http_status_codes.replace(" ", "").split(",");
  568. }
  569. this.settings.http_success = http_status_codes;
  570. this.callFlash("SetHTTPSuccess", [http_status_codes]);
  571. };
  572. // Public: setDebugEnabled changes the debug_enabled setting
  573. SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
  574. this.settings.debug_enabled = debugEnabled;
  575. this.callFlash("SetDebugEnabled", [debugEnabled]);
  576. };
  577. // Public: setButtonImageURL loads a button image sprite
  578. SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
  579. if (buttonImageURL == undefined) {
  580. buttonImageURL = "";
  581. }
  582. this.settings.button_image_url = buttonImageURL;
  583. this.callFlash("SetButtonImageURL", [buttonImageURL]);
  584. };
  585. // Public: setButtonDimensions resizes the Flash Movie and button
  586. SWFUpload.prototype.setButtonDimensions = function (width, height) {
  587. this.settings.button_width = width;
  588. this.settings.button_height = height;
  589. var movie = this.getMovieElement();
  590. if (movie != undefined) {
  591. movie.style.width = width + "px";
  592. movie.style.height = height + "px";
  593. }
  594. this.callFlash("SetButtonDimensions", [width, height]);
  595. };
  596. // Public: setButtonText Changes the text overlaid on the button
  597. SWFUpload.prototype.setButtonText = function (html) {
  598. this.settings.button_text = html;
  599. this.callFlash("SetButtonText", [html]);
  600. };
  601. // Public: setButtonTextPadding changes the top and left padding of the text overlay
  602. SWFUpload.prototype.setButtonTextPadding = function (left, top) {
  603. this.settings.button_text_top_padding = top;
  604. this.settings.button_text_left_padding = left;
  605. this.callFlash("SetButtonTextPadding", [left, top]);
  606. };
  607. // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
  608. SWFUpload.prototype.setButtonTextStyle = function (css) {
  609. this.settings.button_text_style = css;
  610. this.callFlash("SetButtonTextStyle", [css]);
  611. };
  612. // Public: setButtonDisabled disables/enables the button
  613. SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
  614. this.settings.button_disabled = isDisabled;
  615. this.callFlash("SetButtonDisabled", [isDisabled]);
  616. };
  617. // Public: setButtonAction sets the action that occurs when the button is clicked
  618. SWFUpload.prototype.setButtonAction = function (buttonAction) {
  619. this.settings.button_action = buttonAction;
  620. this.callFlash("SetButtonAction", [buttonAction]);
  621. };
  622. // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
  623. SWFUpload.prototype.setButtonCursor = function (cursor) {
  624. this.settings.button_cursor = cursor;
  625. this.callFlash("SetButtonCursor", [cursor]);
  626. };
  627. /* *******************************
  628. Flash Event Interfaces
  629. These functions are used by Flash to trigger the various
  630. events.
  631. All these functions a Private.
  632. Because the ExternalInterface library is buggy the event calls
  633. are added to a queue and the queue then executed by a setTimeout.
  634. This ensures that events are executed in a determinate order and that
  635. the ExternalInterface bugs are avoided.
  636. ******************************* */
  637. SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
  638. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  639. if (argumentArray == undefined) {
  640. argumentArray = [];
  641. } else if (!(argumentArray instanceof Array)) {
  642. argumentArray = [argumentArray];
  643. }
  644. var self = this;
  645. if (typeof this.settings[handlerName] === "function") {
  646. // Queue the event
  647. this.eventQueue.push(function () {
  648. this.settings[handlerName].apply(this, argumentArray);
  649. });
  650. // Execute the next queued event
  651. setTimeout(function () {
  652. self.executeNextEvent();
  653. }, 0);
  654. } else if (this.settings[handlerName] !== null) {
  655. throw "Event handler " + handlerName + " is unknown or is not a function";
  656. }
  657. };
  658. // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
  659. // we must queue them in order to garentee that they are executed in order.
  660. SWFUpload.prototype.executeNextEvent = function () {
  661. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  662. var f = this.eventQueue ? this.eventQueue.shift() : null;
  663. if (typeof(f) === "function") {
  664. f.apply(this);
  665. }
  666. };
  667. // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
  668. // properties that contain characters that are not valid for JavaScript identifiers. To work around this
  669. // the Flash Component escapes the parameter names and we must unescape again before passing them along.
  670. SWFUpload.prototype.unescapeFilePostParams = function (file) {
  671. var reg = /[$]([0-9a-f]{4})/i;
  672. var unescapedPost = {};
  673. var uk;
  674. if (file != undefined) {
  675. for (var k in file.post) {
  676. if (file.post.hasOwnProperty(k)) {
  677. uk = k;
  678. var match;
  679. while ((match = reg.exec(uk)) !== null) {
  680. uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
  681. }
  682. unescapedPost[uk] = file.post[k];
  683. }
  684. }
  685. file.post = unescapedPost;
  686. }
  687. return file;
  688. };
  689. SWFUpload.prototype.flashReady = function () {
  690. // Check that the movie element is loaded correctly with its ExternalInterface methods defined
  691. var movieElement = this.getMovieElement();
  692. // Pro-actively unhook all the Flash functions
  693. if (typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  694. this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
  695. for (var key in movieElement) {
  696. try {
  697. if (typeof(movieElement[key]) === "function") {
  698. movieElement[key] = null;
  699. }
  700. } catch (ex) {
  701. }
  702. }
  703. }
  704. this.queueEvent("swfupload_loaded_handler");
  705. };
  706. /* This is a chance to do something before the browse window opens */
  707. SWFUpload.prototype.fileDialogStart = function () {
  708. this.queueEvent("file_dialog_start_handler");
  709. };
  710. /* Called when a file is successfully added to the queue. */
  711. SWFUpload.prototype.fileQueued = function (file) {
  712. file = this.unescapeFilePostParams(file);
  713. this.queueEvent("file_queued_handler", file);
  714. };
  715. /* Handle errors that occur when an attempt to queue a file fails. */
  716. SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
  717. file = this.unescapeFilePostParams(file);
  718. this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
  719. };
  720. /* Called after the file dialog has closed and the selected files have been queued.
  721. You could call startUpload here if you want the queued files to begin uploading immediately. */
  722. SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued) {
  723. this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued]);
  724. };
  725. SWFUpload.prototype.uploadStart = function (file) {
  726. file = this.unescapeFilePostParams(file);
  727. this.queueEvent("return_upload_start_handler", file);
  728. };
  729. SWFUpload.prototype.returnUploadStart = function (file) {
  730. var returnValue;
  731. if (typeof this.settings.upload_start_handler === "function") {
  732. file = this.unescapeFilePostParams(file);
  733. returnValue = this.settings.upload_start_handler.call(this, file);
  734. } else if (this.settings.upload_start_handler != undefined) {
  735. throw "upload_start_handler must be a function";
  736. }
  737. // Convert undefined to true so if nothing is returned from the upload_start_handler it is
  738. // interpretted as 'true'.
  739. if (returnValue === undefined) {
  740. returnValue = true;
  741. }
  742. returnValue = !!returnValue;
  743. this.callFlash("ReturnUploadStart", [returnValue]);
  744. };
  745. SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
  746. file = this.unescapeFilePostParams(file);
  747. this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
  748. };
  749. SWFUpload.prototype.uploadError = function (file, errorCode, message) {
  750. file = this.unescapeFilePostParams(file);
  751. this.queueEvent("upload_error_handler", [file, errorCode, message]);
  752. };
  753. SWFUpload.prototype.uploadSuccess = function (file, serverData) {
  754. file = this.unescapeFilePostParams(file);
  755. this.queueEvent("upload_success_handler", [file, serverData]);
  756. };
  757. SWFUpload.prototype.uploadComplete = function (file) {
  758. file = this.unescapeFilePostParams(file);
  759. this.queueEvent("upload_complete_handler", file);
  760. };
  761. /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
  762. internal debug console. You can override this event and have messages written where you want. */
  763. SWFUpload.prototype.debug = function (message) {
  764. this.queueEvent("debug_handler", message);
  765. };
  766. /* **********************************
  767. Debug Console
  768. The debug console is a self contained, in page location
  769. for debug message to be sent. The Debug Console adds
  770. itself to the body if necessary.
  771. The console is automatically scrolled as messages appear.
  772. If you are using your own debug handler or when you deploy to production and
  773. have debug disabled you can remove these functions to reduce the file size
  774. and complexity.
  775. ********************************** */
  776. // Private: debugMessage is the default debug_handler. If you want to print debug messages
  777. // call the debug() function. When overriding the function your own function should
  778. // check to see if the debug setting is true before outputting debug information.
  779. SWFUpload.prototype.debugMessage = function (message) {
  780. if (this.settings.debug) {
  781. var exceptionMessage, exceptionValues = [];
  782. // Check for an exception object and print it nicely
  783. if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
  784. for (var key in message) {
  785. if (message.hasOwnProperty(key)) {
  786. exceptionValues.push(key + ": " + message[key]);
  787. }
  788. }
  789. exceptionMessage = exceptionValues.join("\n") || "";
  790. exceptionValues = exceptionMessage.split("\n");
  791. exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
  792. SWFUpload.Console.writeLine(exceptionMessage);
  793. } else {
  794. SWFUpload.Console.writeLine(message);
  795. }
  796. }
  797. };
  798. SWFUpload.Console = {};
  799. SWFUpload.Console.writeLine = function (message) {
  800. var console, documentForm;
  801. try {
  802. console = document.getElementById("SWFUpload_Console");
  803. if (!console) {
  804. documentForm = document.createElement("form");
  805. document.getElementsByTagName("body")[0].appendChild(documentForm);
  806. console = document.createElement("textarea");
  807. console.id = "SWFUpload_Console";
  808. console.style.fontFamily = "monospace";
  809. console.setAttribute("wrap", "off");
  810. console.wrap = "off";
  811. console.style.overflow = "auto";
  812. console.style.width = "700px";
  813. console.style.height = "350px";
  814. console.style.margin = "5px";
  815. documentForm.appendChild(console);
  816. }
  817. console.value += message + "\n";
  818. console.scrollTop = console.scrollHeight - console.clientHeight;
  819. } catch (ex) {
  820. alert("Exception: " + ex.name + " Message: " + ex.message);
  821. }
  822. };