PageRenderTime 58ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/core/swfupload.js

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