unpack_swfupload.js 36 KB

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