multiimage.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  1. /*******************************************************************************
  2. * KindEditor - WYSIWYG HTML Editor for Internet
  3. * Copyright (C) 2006-2011 kindsoft.net
  4. *
  5. * @author Roddy <luolonghao@gmail.com>
  6. * @site http://www.kindsoft.net/
  7. * @licence http://www.kindsoft.net/license.php
  8. *******************************************************************************/
  9. (function (K) {
  10. function KSWFUpload(options) {
  11. this.init(options);
  12. }
  13. K.extend(KSWFUpload, {
  14. init: function (options) {
  15. var self = this;
  16. options.afterError = options.afterError || function (str) {
  17. alert(str);
  18. };
  19. self.options = options;
  20. self.progressbars = {};
  21. // template
  22. self.div = K(options.container).html([
  23. '<div class="ke-swfupload">',
  24. '<div class="ke-swfupload-top">',
  25. '<div class="ke-inline-block ke-swfupload-button">',
  26. '<input type="button" value="Browse" />',
  27. '</div>',
  28. '<div class="ke-inline-block ke-swfupload-desc">' + options.uploadDesc + '</div>',
  29. '<span class="ke-button-common ke-button-outer ke-swfupload-startupload">',
  30. '<input type="button" class="ke-button-common ke-button" value="' + options.startButtonValue + '" />',
  31. '</span>',
  32. '</div>',
  33. '<div class="ke-swfupload-body"></div>',
  34. '</div>'
  35. ].join(''));
  36. self.bodyDiv = K('.ke-swfupload-body', self.div);
  37. function showError(itemDiv, msg) {
  38. K('.ke-status > div', itemDiv).hide();
  39. K('.ke-message', itemDiv).addClass('ke-error').show().html(K.escape(msg));
  40. }
  41. var settings = {
  42. debug: false,
  43. upload_url: options.uploadUrl,
  44. flash_url: options.flashUrl,
  45. file_post_name: options.filePostName,
  46. button_placeholder: K('.ke-swfupload-button > input', self.div)[0],
  47. button_image_url: options.buttonImageUrl,
  48. button_width: options.buttonWidth,
  49. button_height: options.buttonHeight,
  50. button_cursor: SWFUpload.CURSOR.HAND,
  51. file_types: options.fileTypes,
  52. file_types_description: options.fileTypesDesc,
  53. file_upload_limit: options.fileUploadLimit,
  54. file_size_limit: options.fileSizeLimit,
  55. post_params: options.postParams,
  56. file_queued_handler: function (file) {
  57. file.url = self.options.fileIconUrl;
  58. self.appendFile(file);
  59. },
  60. file_queue_error_handler: function (file, errorCode, message) {
  61. var errorName = '';
  62. switch (errorCode) {
  63. case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
  64. errorName = options.queueLimitExceeded;
  65. break;
  66. case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
  67. errorName = options.fileExceedsSizeLimit;
  68. break;
  69. case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
  70. errorName = options.zeroByteFile;
  71. break;
  72. case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
  73. errorName = options.invalidFiletype;
  74. break;
  75. default:
  76. errorName = options.unknownError;
  77. break;
  78. }
  79. K.DEBUG && alert(errorName);
  80. },
  81. upload_start_handler: function (file) {
  82. var self = this;
  83. var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv);
  84. K('.ke-status > div', itemDiv).hide();
  85. K('.ke-progressbar', itemDiv).show();
  86. },
  87. upload_progress_handler: function (file, bytesLoaded, bytesTotal) {
  88. var percent = Math.round(bytesLoaded * 100 / bytesTotal);
  89. var progressbar = self.progressbars[file.id];
  90. progressbar.bar.css('width', Math.round(percent * 80 / 100) + 'px');
  91. progressbar.percent.html(percent + '%');
  92. },
  93. upload_error_handler: function (file, errorCode, message) {
  94. if (file && file.filestatus == SWFUpload.FILE_STATUS.ERROR) {
  95. var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
  96. showError(itemDiv, self.options.errorMessage);
  97. }
  98. },
  99. upload_success_handler: function (file, serverData) {
  100. var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
  101. var data = {};
  102. try {
  103. data = K.json(serverData);
  104. } catch (e) {
  105. self.options.afterError.call(this, '<!doctype html><html>' + serverData + '</html>');
  106. }
  107. if (data.error !== 0) {
  108. showError(itemDiv, K.DEBUG ? data.message : self.options.errorMessage);
  109. return;
  110. }
  111. file.url = data.url;
  112. K('.ke-img', itemDiv).attr('src', file.url).attr('data-status', file.filestatus).data('data', data);
  113. K('.ke-status > div', itemDiv).hide();
  114. }
  115. };
  116. self.swfu = new SWFUpload(settings);
  117. K('.ke-swfupload-startupload input', self.div).click(function () {
  118. self.swfu.startUpload();
  119. });
  120. },
  121. getUrlList: function () {
  122. var list = [];
  123. K('.ke-img', self.bodyDiv).each(function () {
  124. var img = K(this);
  125. var status = img.attr('data-status');
  126. if (status == SWFUpload.FILE_STATUS.COMPLETE) {
  127. list.push(img.data('data'));
  128. }
  129. });
  130. return list;
  131. },
  132. removeFile: function (fileId) {
  133. var self = this;
  134. self.swfu.cancelUpload(fileId);
  135. var itemDiv = K('div[data-id="' + fileId + '"]', self.bodyDiv);
  136. K('.ke-photo', itemDiv).unbind();
  137. K('.ke-delete', itemDiv).unbind();
  138. itemDiv.remove();
  139. },
  140. removeFiles: function () {
  141. var self = this;
  142. K('.ke-item', self.bodyDiv).each(function () {
  143. self.removeFile(K(this).attr('data-id'));
  144. });
  145. },
  146. appendFile: function (file) {
  147. var self = this;
  148. var itemDiv = K('<div class="ke-inline-block ke-item" data-id="' + file.id + '"></div>');
  149. self.bodyDiv.append(itemDiv);
  150. var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
  151. .mouseover(function (e) {
  152. K(this).addClass('ke-on');
  153. })
  154. .mouseout(function (e) {
  155. K(this).removeClass('ke-on');
  156. });
  157. itemDiv.append(photoDiv);
  158. var img = K('<img src="' + file.url + '" class="ke-img" data-status="' + file.filestatus + '" width="80" height="80" alt="' + file.name + '" />');
  159. photoDiv.append(img);
  160. K('<span class="ke-delete"></span>').appendTo(photoDiv).click(function () {
  161. self.removeFile(file.id);
  162. });
  163. var statusDiv = K('<div class="ke-status"></div>').appendTo(photoDiv);
  164. // progressbar
  165. K(['<div class="ke-progressbar">',
  166. '<div class="ke-progressbar-bar"><div class="ke-progressbar-bar-inner"></div></div>',
  167. '<div class="ke-progressbar-percent">0%</div></div>'].join('')).hide().appendTo(statusDiv);
  168. // message
  169. K('<div class="ke-message">' + self.options.pendingMessage + '</div>').appendTo(statusDiv);
  170. itemDiv.append('<div class="ke-name">' + file.name + '</div>');
  171. self.progressbars[file.id] = {
  172. bar: K('.ke-progressbar-bar-inner', photoDiv),
  173. percent: K('.ke-progressbar-percent', photoDiv)
  174. };
  175. },
  176. remove: function () {
  177. this.removeFiles();
  178. this.swfu.destroy();
  179. this.div.html('');
  180. }
  181. });
  182. K.swfupload = function (element, options) {
  183. return new KSWFUpload(element, options);
  184. };
  185. })(KindEditor);
  186. KindEditor.plugin('multiimage', function (K) {
  187. var self = this, name = 'multiimage',
  188. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  189. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
  190. imgPath = self.pluginsPath + 'multiimage/images/',
  191. imageSizeLimit = K.undef(self.imageSizeLimit, '1MB'),
  192. imageFileTypes = K.undef(self.imageFileTypes, '*.jpg;*.gif;*.png'),
  193. imageUploadLimit = K.undef(self.imageUploadLimit, 20),
  194. filePostName = K.undef(self.filePostName, 'imgFile'),
  195. lang = self.lang(name + '.');
  196. self.plugin.multiImageDialog = function (options) {
  197. var clickFn = options.clickFn,
  198. uploadDesc = K.tmpl(lang.uploadDesc, {uploadLimit: imageUploadLimit, sizeLimit: imageSizeLimit});
  199. var html = [
  200. '<div style="padding:20px;">',
  201. '<div class="swfupload">',
  202. '</div>',
  203. '</div>'
  204. ].join('');
  205. var dialog = self.createDialog({
  206. name: name,
  207. width: 650,
  208. height: 510,
  209. title: self.lang(name),
  210. body: html,
  211. previewBtn: {
  212. name: lang.insertAll,
  213. click: function (e) {
  214. clickFn.call(self, swfupload.getUrlList());
  215. }
  216. },
  217. yesBtn: {
  218. name: lang.clearAll,
  219. click: function (e) {
  220. swfupload.removeFiles();
  221. }
  222. },
  223. beforeRemove: function () {
  224. // IE9 bugfix: https://github.com/kindsoft/kindeditor/issues/72
  225. if (!K.IE || K.V <= 8) {
  226. swfupload.remove();
  227. }
  228. }
  229. }),
  230. div = dialog.div;
  231. var swfupload = K.swfupload({
  232. container: K('.swfupload', div),
  233. buttonImageUrl: imgPath + (self.langType == 'zh-CN' ? 'select-files-zh-CN.png' : 'select-files-en.png'),
  234. buttonWidth: self.langType == 'zh-CN' ? 72 : 88,
  235. buttonHeight: 23,
  236. fileIconUrl: imgPath + 'image.png',
  237. uploadDesc: uploadDesc,
  238. startButtonValue: lang.startUpload,
  239. uploadUrl: K.addParam(uploadJson, 'dir=image'),
  240. flashUrl: imgPath + 'swfupload.swf',
  241. filePostName: filePostName,
  242. fileTypes: '*.jpg;*.jpeg;*.gif;*.png;*.bmp',
  243. fileTypesDesc: 'Image Files',
  244. fileUploadLimit: imageUploadLimit,
  245. fileSizeLimit: imageSizeLimit,
  246. postParams: K.undef(self.extraFileUploadParams, {}),
  247. queueLimitExceeded: lang.queueLimitExceeded,
  248. fileExceedsSizeLimit: lang.fileExceedsSizeLimit,
  249. zeroByteFile: lang.zeroByteFile,
  250. invalidFiletype: lang.invalidFiletype,
  251. unknownError: lang.unknownError,
  252. pendingMessage: lang.pending,
  253. errorMessage: lang.uploadError,
  254. afterError: function (html) {
  255. self.errorDialog(html);
  256. }
  257. });
  258. return dialog;
  259. };
  260. self.clickToolbar(name, function () {
  261. self.plugin.multiImageDialog({
  262. clickFn: function (urlList) {
  263. if (urlList.length === 0) {
  264. return;
  265. }
  266. K.each(urlList, function (i, data) {
  267. if (self.afterUpload) {
  268. self.afterUpload.call(self, data.url, data, 'multiimage');
  269. }
  270. self.exec('insertimage', data.url, data.title, data.width, data.height, data.border, data.align);
  271. });
  272. // Bugfix: [Firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hideDialog
  273. setTimeout(function () {
  274. self.hideDialog().focus();
  275. }, 0);
  276. }
  277. });
  278. });
  279. });
  280. /**
  281. * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
  282. *
  283. * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
  284. *
  285. * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz閚 and Mammon Media and is released under the MIT License:
  286. * http://www.opensource.org/licenses/mit-license.php
  287. *
  288. * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
  289. * http://www.opensource.org/licenses/mit-license.php
  290. *
  291. */
  292. /* ******************* */
  293. /* Constructor & Init */
  294. /* ******************* */
  295. (function () {
  296. window.SWFUpload = function (settings) {
  297. this.initSWFUpload(settings);
  298. };
  299. SWFUpload.prototype.initSWFUpload = function (settings) {
  300. try {
  301. this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
  302. this.settings = settings;
  303. this.eventQueue = [];
  304. this.movieName = "KindEditor_SWFUpload_" + SWFUpload.movieCount++;
  305. this.movieElement = null;
  306. // Setup global control tracking
  307. SWFUpload.instances[this.movieName] = this;
  308. // Load the settings. Load the Flash movie.
  309. this.initSettings();
  310. this.loadFlash();
  311. this.displayDebugInfo();
  312. } catch (ex) {
  313. delete SWFUpload.instances[this.movieName];
  314. throw ex;
  315. }
  316. };
  317. /* *************** */
  318. /* Static Members */
  319. /* *************** */
  320. SWFUpload.instances = {};
  321. SWFUpload.movieCount = 0;
  322. SWFUpload.version = "2.2.0 2009-03-25";
  323. SWFUpload.QUEUE_ERROR = {
  324. QUEUE_LIMIT_EXCEEDED: -100,
  325. FILE_EXCEEDS_SIZE_LIMIT: -110,
  326. ZERO_BYTE_FILE: -120,
  327. INVALID_FILETYPE: -130
  328. };
  329. SWFUpload.UPLOAD_ERROR = {
  330. HTTP_ERROR: -200,
  331. MISSING_UPLOAD_URL: -210,
  332. IO_ERROR: -220,
  333. SECURITY_ERROR: -230,
  334. UPLOAD_LIMIT_EXCEEDED: -240,
  335. UPLOAD_FAILED: -250,
  336. SPECIFIED_FILE_ID_NOT_FOUND: -260,
  337. FILE_VALIDATION_FAILED: -270,
  338. FILE_CANCELLED: -280,
  339. UPLOAD_STOPPED: -290
  340. };
  341. SWFUpload.FILE_STATUS = {
  342. QUEUED: -1,
  343. IN_PROGRESS: -2,
  344. ERROR: -3,
  345. COMPLETE: -4,
  346. CANCELLED: -5
  347. };
  348. SWFUpload.BUTTON_ACTION = {
  349. SELECT_FILE: -100,
  350. SELECT_FILES: -110,
  351. START_UPLOAD: -120
  352. };
  353. SWFUpload.CURSOR = {
  354. ARROW: -1,
  355. HAND: -2
  356. };
  357. SWFUpload.WINDOW_MODE = {
  358. WINDOW: "window",
  359. TRANSPARENT: "transparent",
  360. OPAQUE: "opaque"
  361. };
  362. // Private: takes a URL, determines if it is relative and converts to an absolute URL
  363. // using the current site. Only processes the URL if it can, otherwise returns the URL untouched
  364. SWFUpload.completeURL = function (url) {
  365. if (typeof (url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
  366. return url;
  367. }
  368. var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
  369. var indexSlash = window.location.pathname.lastIndexOf("/");
  370. if (indexSlash <= 0) {
  371. path = "/";
  372. } else {
  373. path = window.location.pathname.substr(0, indexSlash) + "/";
  374. }
  375. return /*currentURL +*/ path + url;
  376. };
  377. /* ******************** */
  378. /* Instance Members */
  379. /* ******************** */
  380. // Private: initSettings ensures that all the
  381. // settings are set, getting a default value if one was not assigned.
  382. SWFUpload.prototype.initSettings = function () {
  383. this.ensureDefault = function (settingName, defaultValue) {
  384. this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
  385. };
  386. // Upload backend settings
  387. this.ensureDefault("upload_url", "");
  388. this.ensureDefault("preserve_relative_urls", false);
  389. this.ensureDefault("file_post_name", "Filedata");
  390. this.ensureDefault("post_params", {});
  391. this.ensureDefault("use_query_string", false);
  392. this.ensureDefault("requeue_on_error", false);
  393. this.ensureDefault("http_success", []);
  394. this.ensureDefault("assume_success_timeout", 0);
  395. // File Settings
  396. this.ensureDefault("file_types", "*.*");
  397. this.ensureDefault("file_types_description", "All Files");
  398. this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
  399. this.ensureDefault("file_upload_limit", 0);
  400. this.ensureDefault("file_queue_limit", 0);
  401. // Flash Settings
  402. this.ensureDefault("flash_url", "swfupload.swf");
  403. this.ensureDefault("prevent_swf_caching", true);
  404. // Button Settings
  405. this.ensureDefault("button_image_url", "");
  406. this.ensureDefault("button_width", 1);
  407. this.ensureDefault("button_height", 1);
  408. this.ensureDefault("button_text", "");
  409. this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
  410. this.ensureDefault("button_text_top_padding", 0);
  411. this.ensureDefault("button_text_left_padding", 0);
  412. this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
  413. this.ensureDefault("button_disabled", false);
  414. this.ensureDefault("button_placeholder_id", "");
  415. this.ensureDefault("button_placeholder", null);
  416. this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
  417. this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
  418. // Debug Settings
  419. this.ensureDefault("debug", false);
  420. this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
  421. // Event Handlers
  422. this.settings.return_upload_start_handler = this.returnUploadStart;
  423. this.ensureDefault("swfupload_loaded_handler", null);
  424. this.ensureDefault("file_dialog_start_handler", null);
  425. this.ensureDefault("file_queued_handler", null);
  426. this.ensureDefault("file_queue_error_handler", null);
  427. this.ensureDefault("file_dialog_complete_handler", null);
  428. this.ensureDefault("upload_start_handler", null);
  429. this.ensureDefault("upload_progress_handler", null);
  430. this.ensureDefault("upload_error_handler", null);
  431. this.ensureDefault("upload_success_handler", null);
  432. this.ensureDefault("upload_complete_handler", null);
  433. this.ensureDefault("debug_handler", this.debugMessage);
  434. this.ensureDefault("custom_settings", {});
  435. // Other settings
  436. this.customSettings = this.settings.custom_settings;
  437. // Update the flash url if needed
  438. if (!!this.settings.prevent_swf_caching) {
  439. this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
  440. }
  441. if (!this.settings.preserve_relative_urls) {
  442. //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it
  443. this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
  444. this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
  445. }
  446. delete this.ensureDefault;
  447. };
  448. // Private: loadFlash replaces the button_placeholder element with the flash movie.
  449. SWFUpload.prototype.loadFlash = function () {
  450. var targetElement, tempParent;
  451. // Make sure an element with the ID we are going to use doesn't already exist
  452. if (document.getElementById(this.movieName) !== null) {
  453. throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
  454. }
  455. // Get the element where we will be placing the flash movie
  456. targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
  457. if (targetElement == undefined) {
  458. throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
  459. }
  460. // Append the container and load the flash
  461. tempParent = document.createElement("div");
  462. tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
  463. targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
  464. // Fix IE Flash/Form bug
  465. if (window[this.movieName] == undefined) {
  466. window[this.movieName] = this.getMovieElement();
  467. }
  468. };
  469. // Private: getFlashHTML generates the object tag needed to embed the flash in to the document
  470. SWFUpload.prototype.getFlashHTML = function () {
  471. // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
  472. // Fix bug for IE9
  473. // http://www.kindsoft.net/view.php?bbsid=7&postid=5825&pagenum=1
  474. var classid = '';
  475. if (KindEditor.IE && KindEditor.V > 8) {
  476. classid = ' classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
  477. }
  478. return ['<object id="', this.movieName, '"' + classid + ' type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
  479. '<param name="wmode" value="', this.settings.button_window_mode, '" />',
  480. '<param name="movie" value="', this.settings.flash_url, '" />',
  481. '<param name="quality" value="high" />',
  482. '<param name="menu" value="false" />',
  483. '<param name="allowScriptAccess" value="always" />',
  484. '<param name="flashvars" value="' + this.getFlashVars() + '" />',
  485. '</object>'].join("");
  486. };
  487. // Private: getFlashVars builds the parameter string that will be passed
  488. // to flash in the flashvars param.
  489. SWFUpload.prototype.getFlashVars = function () {
  490. // Build a string from the post param object
  491. var paramString = this.buildParamString();
  492. var httpSuccessString = this.settings.http_success.join(",");
  493. // Build the parameter string
  494. return ["movieName=", encodeURIComponent(this.movieName),
  495. "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
  496. "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
  497. "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
  498. "&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
  499. "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
  500. "&amp;params=", encodeURIComponent(paramString),
  501. "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
  502. "&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
  503. "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
  504. "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
  505. "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
  506. "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
  507. "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
  508. "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
  509. "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
  510. "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
  511. "&amp;buttonText=", encodeURIComponent(this.settings.button_text),
  512. "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
  513. "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
  514. "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
  515. "&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
  516. "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
  517. "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
  518. ].join("");
  519. };
  520. // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
  521. // The element is cached after the first lookup
  522. SWFUpload.prototype.getMovieElement = function () {
  523. if (this.movieElement == undefined) {
  524. this.movieElement = document.getElementById(this.movieName);
  525. }
  526. if (this.movieElement === null) {
  527. throw "Could not find Flash element";
  528. }
  529. return this.movieElement;
  530. };
  531. // Private: buildParamString takes the name/value pairs in the post_params setting object
  532. // and joins them up in to a string formatted "name=value&amp;name=value"
  533. SWFUpload.prototype.buildParamString = function () {
  534. var postParams = this.settings.post_params;
  535. var paramStringPairs = [];
  536. if (typeof (postParams) === "object") {
  537. for (var name in postParams) {
  538. if (postParams.hasOwnProperty(name)) {
  539. paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
  540. }
  541. }
  542. }
  543. return paramStringPairs.join("&amp;");
  544. };
  545. // Public: Used to remove a SWFUpload instance from the page. This method strives to remove
  546. // all references to the SWF, and other objects so memory is properly freed.
  547. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
  548. // Credits: Major improvements provided by steffen
  549. SWFUpload.prototype.destroy = function () {
  550. try {
  551. // Make sure Flash is done before we try to remove it
  552. this.cancelUpload(null, false);
  553. // Remove the SWFUpload DOM nodes
  554. var movieElement = null;
  555. movieElement = this.getMovieElement();
  556. if (movieElement && typeof (movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  557. // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
  558. for (var i in movieElement) {
  559. try {
  560. if (typeof (movieElement[i]) === "function") {
  561. movieElement[i] = null;
  562. }
  563. } catch (ex1) {
  564. }
  565. }
  566. // Remove the Movie Element from the page
  567. try {
  568. movieElement.parentNode.removeChild(movieElement);
  569. } catch (ex) {
  570. }
  571. }
  572. // Remove IE form fix reference
  573. window[this.movieName] = null;
  574. // Destroy other references
  575. SWFUpload.instances[this.movieName] = null;
  576. delete SWFUpload.instances[this.movieName];
  577. this.movieElement = null;
  578. this.settings = null;
  579. this.customSettings = null;
  580. this.eventQueue = null;
  581. this.movieName = null;
  582. return true;
  583. } catch (ex2) {
  584. return false;
  585. }
  586. };
  587. // Public: displayDebugInfo prints out settings and configuration
  588. // information about this SWFUpload instance.
  589. // This function (and any references to it) can be deleted when placing
  590. // SWFUpload in production.
  591. SWFUpload.prototype.displayDebugInfo = function () {
  592. this.debug(
  593. [
  594. "---SWFUpload Instance Info---\n",
  595. "Version: ", SWFUpload.version, "\n",
  596. "Movie Name: ", this.movieName, "\n",
  597. "Settings:\n",
  598. "\t", "upload_url: ", this.settings.upload_url, "\n",
  599. "\t", "flash_url: ", this.settings.flash_url, "\n",
  600. "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
  601. "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
  602. "\t", "http_success: ", this.settings.http_success.join(", "), "\n",
  603. "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n",
  604. "\t", "file_post_name: ", this.settings.file_post_name, "\n",
  605. "\t", "post_params: ", this.settings.post_params.toString(), "\n",
  606. "\t", "file_types: ", this.settings.file_types, "\n",
  607. "\t", "file_types_description: ", this.settings.file_types_description, "\n",
  608. "\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
  609. "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
  610. "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
  611. "\t", "debug: ", this.settings.debug.toString(), "\n",
  612. "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
  613. "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
  614. "\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
  615. "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
  616. "\t", "button_width: ", this.settings.button_width.toString(), "\n",
  617. "\t", "button_height: ", this.settings.button_height.toString(), "\n",
  618. "\t", "button_text: ", this.settings.button_text.toString(), "\n",
  619. "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
  620. "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
  621. "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
  622. "\t", "button_action: ", this.settings.button_action.toString(), "\n",
  623. "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
  624. "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
  625. "Event Handlers:\n",
  626. "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
  627. "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
  628. "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
  629. "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
  630. "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
  631. "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
  632. "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
  633. "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
  634. "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
  635. "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n"
  636. ].join("")
  637. );
  638. };
  639. /* Note: addSetting and getSetting are no longer used by SWFUpload but are included
  640. the maintain v2 API compatibility
  641. */
  642. // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
  643. SWFUpload.prototype.addSetting = function (name, value, default_value) {
  644. if (value == undefined) {
  645. return (this.settings[name] = default_value);
  646. } else {
  647. return (this.settings[name] = value);
  648. }
  649. };
  650. // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
  651. SWFUpload.prototype.getSetting = function (name) {
  652. if (this.settings[name] != undefined) {
  653. return this.settings[name];
  654. }
  655. return "";
  656. };
  657. // Private: callFlash handles function calls made to the Flash element.
  658. // Calls are made with a setTimeout for some functions to work around
  659. // bugs in the ExternalInterface library.
  660. SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
  661. argumentArray = argumentArray || [];
  662. var movieElement = this.getMovieElement();
  663. var returnValue, returnString;
  664. // Flash's method if calling ExternalInterface methods (code adapted from MooTools).
  665. try {
  666. returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
  667. returnValue = eval(returnString);
  668. } catch (ex) {
  669. throw "Call to " + functionName + " failed";
  670. }
  671. // Unescape file post param values
  672. if (returnValue != undefined && typeof returnValue.post === "object") {
  673. returnValue = this.unescapeFilePostParams(returnValue);
  674. }
  675. return returnValue;
  676. };
  677. /* *****************************
  678. -- Flash control methods --
  679. Your UI should use these
  680. to operate SWFUpload
  681. ***************************** */
  682. // WARNING: this function does not work in Flash Player 10
  683. // Public: selectFile causes a File Selection Dialog window to appear. This
  684. // dialog only allows 1 file to be selected.
  685. SWFUpload.prototype.selectFile = function () {
  686. this.callFlash("SelectFile");
  687. };
  688. // WARNING: this function does not work in Flash Player 10
  689. // Public: selectFiles causes a File Selection Dialog window to appear/ This
  690. // dialog allows the user to select any number of files
  691. // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
  692. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around
  693. // for this bug.
  694. SWFUpload.prototype.selectFiles = function () {
  695. this.callFlash("SelectFiles");
  696. };
  697. // Public: startUpload starts uploading the first file in the queue unless
  698. // the optional parameter 'fileID' specifies the ID
  699. SWFUpload.prototype.startUpload = function (fileID) {
  700. this.callFlash("StartUpload", [fileID]);
  701. };
  702. // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index.
  703. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
  704. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
  705. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
  706. if (triggerErrorEvent !== false) {
  707. triggerErrorEvent = true;
  708. }
  709. this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
  710. };
  711. // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
  712. // If nothing is currently uploading then nothing happens.
  713. SWFUpload.prototype.stopUpload = function () {
  714. this.callFlash("StopUpload");
  715. };
  716. /* ************************
  717. * Settings methods
  718. * These methods change the SWFUpload settings.
  719. * SWFUpload settings should not be changed directly on the settings object
  720. * since many of the settings need to be passed to Flash in order to take
  721. * effect.
  722. * *********************** */
  723. // Public: getStats gets the file statistics object.
  724. SWFUpload.prototype.getStats = function () {
  725. return this.callFlash("GetStats");
  726. };
  727. // Public: setStats changes the SWFUpload statistics. You shouldn't need to
  728. // change the statistics but you can. Changing the statistics does not
  729. // affect SWFUpload accept for the successful_uploads count which is used
  730. // by the upload_limit setting to determine how many files the user may upload.
  731. SWFUpload.prototype.setStats = function (statsObject) {
  732. this.callFlash("SetStats", [statsObject]);
  733. };
  734. // Public: getFile retrieves a File object by ID or Index. If the file is
  735. // not found then 'null' is returned.
  736. SWFUpload.prototype.getFile = function (fileID) {
  737. if (typeof (fileID) === "number") {
  738. return this.callFlash("GetFileByIndex", [fileID]);
  739. } else {
  740. return this.callFlash("GetFile", [fileID]);
  741. }
  742. };
  743. // Public: addFileParam sets a name/value pair that will be posted with the
  744. // file specified by the Files ID. If the name already exists then the
  745. // exiting value will be overwritten.
  746. SWFUpload.prototype.addFileParam = function (fileID, name, value) {
  747. return this.callFlash("AddFileParam", [fileID, name, value]);
  748. };
  749. // Public: removeFileParam removes a previously set (by addFileParam) name/value
  750. // pair from the specified file.
  751. SWFUpload.prototype.removeFileParam = function (fileID, name) {
  752. this.callFlash("RemoveFileParam", [fileID, name]);
  753. };
  754. // Public: setUploadUrl changes the upload_url setting.
  755. SWFUpload.prototype.setUploadURL = function (url) {
  756. this.settings.upload_url = url.toString();
  757. this.callFlash("SetUploadURL", [url]);
  758. };
  759. // Public: setPostParams changes the post_params setting
  760. SWFUpload.prototype.setPostParams = function (paramsObject) {
  761. this.settings.post_params = paramsObject;
  762. this.callFlash("SetPostParams", [paramsObject]);
  763. };
  764. // Public: addPostParam adds post name/value pair. Each name can have only one value.
  765. SWFUpload.prototype.addPostParam = function (name, value) {
  766. this.settings.post_params[name] = value;
  767. this.callFlash("SetPostParams", [this.settings.post_params]);
  768. };
  769. // Public: removePostParam deletes post name/value pair.
  770. SWFUpload.prototype.removePostParam = function (name) {
  771. delete this.settings.post_params[name];
  772. this.callFlash("SetPostParams", [this.settings.post_params]);
  773. };
  774. // Public: setFileTypes changes the file_types setting and the file_types_description setting
  775. SWFUpload.prototype.setFileTypes = function (types, description) {
  776. this.settings.file_types = types;
  777. this.settings.file_types_description = description;
  778. this.callFlash("SetFileTypes", [types, description]);
  779. };
  780. // Public: setFileSizeLimit changes the file_size_limit setting
  781. SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
  782. this.settings.file_size_limit = fileSizeLimit;
  783. this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
  784. };
  785. // Public: setFileUploadLimit changes the file_upload_limit setting
  786. SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
  787. this.settings.file_upload_limit = fileUploadLimit;
  788. this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
  789. };
  790. // Public: setFileQueueLimit changes the file_queue_limit setting
  791. SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
  792. this.settings.file_queue_limit = fileQueueLimit;
  793. this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
  794. };
  795. // Public: setFilePostName changes the file_post_name setting
  796. SWFUpload.prototype.setFilePostName = function (filePostName) {
  797. this.settings.file_post_name = filePostName;
  798. this.callFlash("SetFilePostName", [filePostName]);
  799. };
  800. // Public: setUseQueryString changes the use_query_string setting
  801. SWFUpload.prototype.setUseQueryString = function (useQueryString) {
  802. this.settings.use_query_string = useQueryString;
  803. this.callFlash("SetUseQueryString", [useQueryString]);
  804. };
  805. // Public: setRequeueOnError changes the requeue_on_error setting
  806. SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
  807. this.settings.requeue_on_error = requeueOnError;
  808. this.callFlash("SetRequeueOnError", [requeueOnError]);
  809. };
  810. // Public: setHTTPSuccess changes the http_success setting
  811. SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
  812. if (typeof http_status_codes === "string") {
  813. http_status_codes = http_status_codes.replace(" ", "").split(",");
  814. }
  815. this.settings.http_success = http_status_codes;
  816. this.callFlash("SetHTTPSuccess", [http_status_codes]);
  817. };
  818. // Public: setHTTPSuccess changes the http_success setting
  819. SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
  820. this.settings.assume_success_timeout = timeout_seconds;
  821. this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
  822. };
  823. // Public: setDebugEnabled changes the debug_enabled setting
  824. SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
  825. this.settings.debug_enabled = debugEnabled;
  826. this.callFlash("SetDebugEnabled", [debugEnabled]);
  827. };
  828. // Public: setButtonImageURL loads a button image sprite
  829. SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
  830. if (buttonImageURL == undefined) {
  831. buttonImageURL = "";
  832. }
  833. this.settings.button_image_url = buttonImageURL;
  834. this.callFlash("SetButtonImageURL", [buttonImageURL]);
  835. };
  836. // Public: setButtonDimensions resizes the Flash Movie and button
  837. SWFUpload.prototype.setButtonDimensions = function (width, height) {
  838. this.settings.button_width = width;
  839. this.settings.button_height = height;
  840. var movie = this.getMovieElement();
  841. if (movie != undefined) {
  842. movie.style.width = width + "px";
  843. movie.style.height = height + "px";
  844. }
  845. this.callFlash("SetButtonDimensions", [width, height]);
  846. };
  847. // Public: setButtonText Changes the text overlaid on the button
  848. SWFUpload.prototype.setButtonText = function (html) {
  849. this.settings.button_text = html;
  850. this.callFlash("SetButtonText", [html]);
  851. };
  852. // Public: setButtonTextPadding changes the top and left padding of the text overlay
  853. SWFUpload.prototype.setButtonTextPadding = function (left, top) {
  854. this.settings.button_text_top_padding = top;
  855. this.settings.button_text_left_padding = left;
  856. this.callFlash("SetButtonTextPadding", [left, top]);
  857. };
  858. // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
  859. SWFUpload.prototype.setButtonTextStyle = function (css) {
  860. this.settings.button_text_style = css;
  861. this.callFlash("SetButtonTextStyle", [css]);
  862. };
  863. // Public: setButtonDisabled disables/enables the button
  864. SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
  865. this.settings.button_disabled = isDisabled;
  866. this.callFlash("SetButtonDisabled", [isDisabled]);
  867. };
  868. // Public: setButtonAction sets the action that occurs when the button is clicked
  869. SWFUpload.prototype.setButtonAction = function (buttonAction) {
  870. this.settings.button_action = buttonAction;
  871. this.callFlash("SetButtonAction", [buttonAction]);
  872. };
  873. // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
  874. SWFUpload.prototype.setButtonCursor = function (cursor) {
  875. this.settings.button_cursor = cursor;
  876. this.callFlash("SetButtonCursor", [cursor]);
  877. };
  878. /* *******************************
  879. Flash Event Interfaces
  880. These functions are used by Flash to trigger the various
  881. events.
  882. All these functions a Private.
  883. Because the ExternalInterface library is buggy the event calls
  884. are added to a queue and the queue then executed by a setTimeout.
  885. This ensures that events are executed in a determinate order and that
  886. the ExternalInterface bugs are avoided.
  887. ******************************* */
  888. SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
  889. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  890. if (argumentArray == undefined) {
  891. argumentArray = [];
  892. } else if (!(argumentArray instanceof Array)) {
  893. argumentArray = [argumentArray];
  894. }
  895. var self = this;
  896. if (typeof this.settings[handlerName] === "function") {
  897. // Queue the event
  898. this.eventQueue.push(function () {
  899. this.settings[handlerName].apply(this, argumentArray);
  900. });
  901. // Execute the next queued event
  902. setTimeout(function () {
  903. self.executeNextEvent();
  904. }, 0);
  905. } else if (this.settings[handlerName] !== null) {
  906. throw "Event handler " + handlerName + " is unknown or is not a function";
  907. }
  908. };
  909. // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
  910. // we must queue them in order to garentee that they are executed in order.
  911. SWFUpload.prototype.executeNextEvent = function () {
  912. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  913. var f = this.eventQueue ? this.eventQueue.shift() : null;
  914. if (typeof (f) === "function") {
  915. f.apply(this);
  916. }
  917. };
  918. // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
  919. // properties that contain characters that are not valid for JavaScript identifiers. To work around this
  920. // the Flash Component escapes the parameter names and we must unescape again before passing them along.
  921. SWFUpload.prototype.unescapeFilePostParams = function (file) {
  922. var reg = /[$]([0-9a-f]{4})/i;
  923. var unescapedPost = {};
  924. var uk;
  925. if (file != undefined) {
  926. for (var k in file.post) {
  927. if (file.post.hasOwnProperty(k)) {
  928. uk = k;
  929. var match;
  930. while ((match = reg.exec(uk)) !== null) {
  931. uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
  932. }
  933. unescapedPost[uk] = file.post[k];
  934. }
  935. }
  936. file.post = unescapedPost;
  937. }
  938. return file;
  939. };
  940. // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
  941. SWFUpload.prototype.testExternalInterface = function () {
  942. try {
  943. return this.callFlash("TestExternalInterface");
  944. } catch (ex) {
  945. return false;
  946. }
  947. };
  948. // Private: This event is called by Flash when it has finished loading. Don't modify this.
  949. // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
  950. SWFUpload.prototype.flashReady = function () {
  951. // Check that the movie element is loaded correctly with its ExternalInterface methods defined
  952. var movieElement = this.getMovieElement();
  953. if (!movieElement) {
  954. this.debug("Flash called back ready but the flash movie can't be found.");
  955. return;
  956. }
  957. this.cleanUp(movieElement);
  958. this.queueEvent("swfupload_loaded_handler");
  959. };
  960. // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
  961. // This function is called by Flash each time the ExternalInterface functions are created.
  962. SWFUpload.prototype.cleanUp = function (movieElement) {
  963. // Pro-actively unhook all the Flash functions
  964. try {
  965. if (this.movieElement && typeof (movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  966. this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
  967. for (var key in movieElement) {
  968. try {
  969. if (typeof (movieElement[key]) === "function") {
  970. movieElement[key] = null;
  971. }
  972. } catch (ex) {
  973. }
  974. }
  975. }
  976. } catch (ex1) {
  977. }
  978. // Fix Flashes own cleanup code so if the SWFMovie was removed from the page
  979. // it doesn't display errors.
  980. window["__flash__removeCallback"] = function (instance, name) {
  981. try {
  982. if (instance) {
  983. instance[name] = null;
  984. }
  985. } catch (flashEx) {
  986. }
  987. };
  988. };
  989. /* This is a chance to do something before the browse window opens */
  990. SWFUpload.prototype.fileDialogStart = function () {
  991. this.queueEvent("file_dialog_start_handler");
  992. };
  993. /* Called when a file is successfully added to the queue. */
  994. SWFUpload.prototype.fileQueued = function (file) {
  995. file = this.unescapeFilePostParams(file);
  996. this.queueEvent("file_queued_handler", file);
  997. };
  998. /* Handle errors that occur when an attempt to queue a file fails. */
  999. SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
  1000. file = this.unescapeFilePostParams(file);
  1001. this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
  1002. };
  1003. /* Called after the file dialog has closed and the selected files have been queued.
  1004. You could call startUpload here if you want the queued files to begin uploading immediately. */
  1005. SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
  1006. this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
  1007. };
  1008. SWFUpload.prototype.uploadStart = function (file) {
  1009. file = this.unescapeFilePostParams(file);
  1010. this.queueEvent("return_upload_start_handler", file);
  1011. };
  1012. SWFUpload.prototype.returnUploadStart = function (file) {
  1013. var returnValue;
  1014. if (typeof this.settings.upload_start_handler === "function") {
  1015. file = this.unescapeFilePostParams(file);
  1016. returnValue = this.settings.upload_start_handler.call(this, file);
  1017. } else if (this.settings.upload_start_handler != undefined) {
  1018. throw "upload_start_handler must be a function";
  1019. }
  1020. // Convert undefined to true so if nothing is returned from the upload_start_handler it is
  1021. // interpretted as 'true'.
  1022. if (returnValue === undefined) {
  1023. returnValue = true;
  1024. }
  1025. returnValue = !!returnValue;
  1026. this.callFlash("ReturnUploadStart", [returnValue]);
  1027. };
  1028. SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
  1029. file = this.unescapeFilePostParams(file);
  1030. this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
  1031. };
  1032. SWFUpload.prototype.uploadError = function (file, errorCode, message) {
  1033. file = this.unescapeFilePostParams(file);
  1034. this.queueEvent("upload_error_handler", [file, errorCode, message]);
  1035. };
  1036. SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
  1037. file = this.unescapeFilePostParams(file);
  1038. this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
  1039. };
  1040. SWFUpload.prototype.uploadComplete = function (file) {
  1041. file = this.unescapeFilePostParams(file);
  1042. this.queueEvent("upload_complete_handler", file);
  1043. };
  1044. /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
  1045. internal debug console. You can override this event and have messages written where you want. */
  1046. SWFUpload.prototype.debug = function (message) {
  1047. this.queueEvent("debug_handler", message);
  1048. };
  1049. /* **********************************
  1050. Debug Console
  1051. The debug console is a self contained, in page location
  1052. for debug message to be sent. The Debug Console adds
  1053. itself to the body if necessary.
  1054. The console is automatically scrolled as messages appear.
  1055. If you are using your own debug handler or when you deploy to production and
  1056. have debug disabled you can remove these functions to reduce the file size
  1057. and complexity.
  1058. ********************************** */
  1059. // Private: debugMessage is the default debug_handler. If you want to print debug messages
  1060. // call the debug() function. When overriding the function your own function should
  1061. // check to see if the debug setting is true before outputting debug information.
  1062. SWFUpload.prototype.debugMessage = function (message) {
  1063. if (this.settings.debug) {
  1064. var exceptionMessage, exceptionValues = [];
  1065. // Check for an exception object and print it nicely
  1066. if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
  1067. for (var key in message) {
  1068. if (message.hasOwnProperty(key)) {
  1069. exceptionValues.push(key + ": " + message[key]);
  1070. }
  1071. }
  1072. exceptionMessage = exceptionValues.join("\n") || "";
  1073. exceptionValues = exceptionMessage.split("\n");
  1074. exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
  1075. SWFUpload.Console.writeLine(exceptionMessage);
  1076. } else {
  1077. SWFUpload.Console.writeLine(message);
  1078. }
  1079. }
  1080. };
  1081. SWFUpload.Console = {};
  1082. SWFUpload.Console.writeLine = function (message) {
  1083. var console, documentForm;
  1084. try {
  1085. console = document.getElementById("SWFUpload_Console");
  1086. if (!console) {
  1087. documentForm = document.createElement("form");
  1088. document.getElementsByTagName("body")[0].appendChild(documentForm);
  1089. console = document.createElement("textarea");
  1090. console.id = "SWFUpload_Console";
  1091. console.style.fontFamily = "monospace";
  1092. console.setAttribute("wrap", "off");
  1093. console.wrap = "off";
  1094. console.style.overflow = "auto";
  1095. console.style.width = "700px";
  1096. console.style.height = "350px";
  1097. console.style.margin = "5px";
  1098. documentForm.appendChild(console);
  1099. }
  1100. console.value += message + "\n";
  1101. console.scrollTop = console.scrollHeight - console.clientHeight;
  1102. } catch (ex) {
  1103. alert("Exception: " + ex.name + " Message: " + ex.message);
  1104. }
  1105. };
  1106. })();
  1107. (function () {
  1108. /*
  1109. Queue Plug-in
  1110. Features:
  1111. *Adds a cancelQueue() method for cancelling the entire queue.
  1112. *All queued files are uploaded when startUpload() is called.
  1113. *If false is returned from uploadComplete then the queue upload is stopped.
  1114. If false is not returned (strict comparison) then the queue upload is continued.
  1115. *Adds a QueueComplete event that is fired when all the queued files have finished uploading.
  1116. Set the event handler with the queue_complete_handler setting.
  1117. */
  1118. if (typeof (SWFUpload) === "function") {
  1119. SWFUpload.queue = {};
  1120. SWFUpload.prototype.initSettings = (function (oldInitSettings) {
  1121. return function () {
  1122. if (typeof (oldInitSettings) === "function") {
  1123. oldInitSettings.call(this);
  1124. }
  1125. this.queueSettings = {};
  1126. this.queueSettings.queue_cancelled_flag = false;
  1127. this.queueSettings.queue_upload_count = 0;
  1128. this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
  1129. this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
  1130. this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
  1131. this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
  1132. this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
  1133. };
  1134. })(SWFUpload.prototype.initSettings);
  1135. SWFUpload.prototype.startUpload = function (fileID) {
  1136. this.queueSettings.queue_cancelled_flag = false;
  1137. this.callFlash("StartUpload", [fileID]);
  1138. };
  1139. SWFUpload.prototype.cancelQueue = function () {
  1140. this.queueSettings.queue_cancelled_flag = true;
  1141. this.stopUpload();
  1142. var stats = this.getStats();
  1143. while (stats.files_queued > 0) {
  1144. this.cancelUpload();
  1145. stats = this.getStats();
  1146. }
  1147. };
  1148. SWFUpload.queue.uploadStartHandler = function (file) {
  1149. var returnValue;
  1150. if (typeof (this.queueSettings.user_upload_start_handler) === "function") {
  1151. returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
  1152. }
  1153. // To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
  1154. returnValue = (returnValue === false) ? false : true;
  1155. this.queueSettings.queue_cancelled_flag = !returnValue;
  1156. return returnValue;
  1157. };
  1158. SWFUpload.queue.uploadCompleteHandler = function (file) {
  1159. var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
  1160. var continueUpload;
  1161. if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
  1162. this.queueSettings.queue_upload_count++;
  1163. }
  1164. if (typeof (user_upload_complete_handler) === "function") {
  1165. continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
  1166. } else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
  1167. // If the file was stopped and re-queued don't restart the upload
  1168. continueUpload = false;
  1169. } else {
  1170. continueUpload = true;
  1171. }
  1172. if (continueUpload) {
  1173. var stats = this.getStats();
  1174. if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
  1175. this.startUpload();
  1176. } else if (this.queueSettings.queue_cancelled_flag === false) {
  1177. this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
  1178. this.queueSettings.queue_upload_count = 0;
  1179. } else {
  1180. this.queueSettings.queue_cancelled_flag = false;
  1181. this.queueSettings.queue_upload_count = 0;
  1182. }
  1183. }
  1184. };
  1185. }
  1186. })();