PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/thirdparty/swfupload/swfupload/swfupload.js

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