You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

980 lines
37 KiB

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