PageRenderTime 115ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/public/cui/plugins/swfupload/swfupload.js

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