multiimage.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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. if (window.SWFUpload) {
  297. return;
  298. }
  299. window.SWFUpload = function (settings) {
  300. this.initSWFUpload(settings);
  301. };
  302. SWFUpload.prototype.initSWFUpload = function (settings) {
  303. try {
  304. this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
  305. this.settings = settings;
  306. this.eventQueue = [];
  307. this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
  308. this.movieElement = null;
  309. // Setup global control tracking
  310. SWFUpload.instances[this.movieName] = this;
  311. // Load the settings. Load the Flash movie.
  312. this.initSettings();
  313. this.loadFlash();
  314. this.displayDebugInfo();
  315. } catch (ex) {
  316. delete SWFUpload.instances[this.movieName];
  317. throw ex;
  318. }
  319. };
  320. /* *************** */
  321. /* Static Members */
  322. /* *************** */
  323. SWFUpload.instances = {};
  324. SWFUpload.movieCount = 0;
  325. SWFUpload.version = "2.2.0 2009-03-25";
  326. SWFUpload.QUEUE_ERROR = {
  327. QUEUE_LIMIT_EXCEEDED : -100,
  328. FILE_EXCEEDS_SIZE_LIMIT : -110,
  329. ZERO_BYTE_FILE : -120,
  330. INVALID_FILETYPE : -130
  331. };
  332. SWFUpload.UPLOAD_ERROR = {
  333. HTTP_ERROR : -200,
  334. MISSING_UPLOAD_URL : -210,
  335. IO_ERROR : -220,
  336. SECURITY_ERROR : -230,
  337. UPLOAD_LIMIT_EXCEEDED : -240,
  338. UPLOAD_FAILED : -250,
  339. SPECIFIED_FILE_ID_NOT_FOUND : -260,
  340. FILE_VALIDATION_FAILED : -270,
  341. FILE_CANCELLED : -280,
  342. UPLOAD_STOPPED : -290
  343. };
  344. SWFUpload.FILE_STATUS = {
  345. QUEUED : -1,
  346. IN_PROGRESS : -2,
  347. ERROR : -3,
  348. COMPLETE : -4,
  349. CANCELLED : -5
  350. };
  351. SWFUpload.BUTTON_ACTION = {
  352. SELECT_FILE : -100,
  353. SELECT_FILES : -110,
  354. START_UPLOAD : -120
  355. };
  356. SWFUpload.CURSOR = {
  357. ARROW : -1,
  358. HAND : -2
  359. };
  360. SWFUpload.WINDOW_MODE = {
  361. WINDOW : "window",
  362. TRANSPARENT : "transparent",
  363. OPAQUE : "opaque"
  364. };
  365. // Private: takes a URL, determines if it is relative and converts to an absolute URL
  366. // using the current site. Only processes the URL if it can, otherwise returns the URL untouched
  367. SWFUpload.completeURL = function(url) {
  368. if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
  369. return url;
  370. }
  371. var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
  372. var indexSlash = window.location.pathname.lastIndexOf("/");
  373. if (indexSlash <= 0) {
  374. path = "/";
  375. } else {
  376. path = window.location.pathname.substr(0, indexSlash) + "/";
  377. }
  378. return /*currentURL +*/ path + url;
  379. };
  380. /* ******************** */
  381. /* Instance Members */
  382. /* ******************** */
  383. // Private: initSettings ensures that all the
  384. // settings are set, getting a default value if one was not assigned.
  385. SWFUpload.prototype.initSettings = function () {
  386. this.ensureDefault = function (settingName, defaultValue) {
  387. this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
  388. };
  389. // Upload backend settings
  390. this.ensureDefault("upload_url", "");
  391. this.ensureDefault("preserve_relative_urls", false);
  392. this.ensureDefault("file_post_name", "Filedata");
  393. this.ensureDefault("post_params", {});
  394. this.ensureDefault("use_query_string", false);
  395. this.ensureDefault("requeue_on_error", false);
  396. this.ensureDefault("http_success", []);
  397. this.ensureDefault("assume_success_timeout", 0);
  398. // File Settings
  399. this.ensureDefault("file_types", "*.*");
  400. this.ensureDefault("file_types_description", "All Files");
  401. this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
  402. this.ensureDefault("file_upload_limit", 0);
  403. this.ensureDefault("file_queue_limit", 0);
  404. // Flash Settings
  405. this.ensureDefault("flash_url", "swfupload.swf");
  406. this.ensureDefault("prevent_swf_caching", true);
  407. // Button Settings
  408. this.ensureDefault("button_image_url", "");
  409. this.ensureDefault("button_width", 1);
  410. this.ensureDefault("button_height", 1);
  411. this.ensureDefault("button_text", "");
  412. this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
  413. this.ensureDefault("button_text_top_padding", 0);
  414. this.ensureDefault("button_text_left_padding", 0);
  415. this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
  416. this.ensureDefault("button_disabled", false);
  417. this.ensureDefault("button_placeholder_id", "");
  418. this.ensureDefault("button_placeholder", null);
  419. this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
  420. this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
  421. // Debug Settings
  422. this.ensureDefault("debug", false);
  423. this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
  424. // Event Handlers
  425. this.settings.return_upload_start_handler = this.returnUploadStart;
  426. this.ensureDefault("swfupload_loaded_handler", null);
  427. this.ensureDefault("file_dialog_start_handler", null);
  428. this.ensureDefault("file_queued_handler", null);
  429. this.ensureDefault("file_queue_error_handler", null);
  430. this.ensureDefault("file_dialog_complete_handler", null);
  431. this.ensureDefault("upload_start_handler", null);
  432. this.ensureDefault("upload_progress_handler", null);
  433. this.ensureDefault("upload_error_handler", null);
  434. this.ensureDefault("upload_success_handler", null);
  435. this.ensureDefault("upload_complete_handler", null);
  436. this.ensureDefault("debug_handler", this.debugMessage);
  437. this.ensureDefault("custom_settings", {});
  438. // Other settings
  439. this.customSettings = this.settings.custom_settings;
  440. // Update the flash url if needed
  441. if (!!this.settings.prevent_swf_caching) {
  442. this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
  443. }
  444. if (!this.settings.preserve_relative_urls) {
  445. //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it
  446. this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
  447. this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
  448. }
  449. delete this.ensureDefault;
  450. };
  451. // Private: loadFlash replaces the button_placeholder element with the flash movie.
  452. SWFUpload.prototype.loadFlash = function () {
  453. var targetElement, tempParent;
  454. // Make sure an element with the ID we are going to use doesn't already exist
  455. if (document.getElementById(this.movieName) !== null) {
  456. throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
  457. }
  458. // Get the element where we will be placing the flash movie
  459. targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
  460. if (targetElement == undefined) {
  461. throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
  462. }
  463. // Append the container and load the flash
  464. tempParent = document.createElement("div");
  465. tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
  466. targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
  467. // Fix IE Flash/Form bug
  468. if (window[this.movieName] == undefined) {
  469. window[this.movieName] = this.getMovieElement();
  470. }
  471. };
  472. // Private: getFlashHTML generates the object tag needed to embed the flash in to the document
  473. SWFUpload.prototype.getFlashHTML = function () {
  474. // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
  475. // Fix bug for IE9
  476. // http://www.kindsoft.net/view.php?bbsid=7&postid=5825&pagenum=1
  477. var classid = '';
  478. if (KindEditor.IE && KindEditor.V > 8) {
  479. classid = ' classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
  480. }
  481. 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">',
  482. '<param name="wmode" value="', this.settings.button_window_mode, '" />',
  483. '<param name="movie" value="', this.settings.flash_url, '" />',
  484. '<param name="quality" value="high" />',
  485. '<param name="menu" value="false" />',
  486. '<param name="allowScriptAccess" value="always" />',
  487. '<param name="flashvars" value="' + this.getFlashVars() + '" />',
  488. '</object>'].join("");
  489. };
  490. // Private: getFlashVars builds the parameter string that will be passed
  491. // to flash in the flashvars param.
  492. SWFUpload.prototype.getFlashVars = function () {
  493. // Build a string from the post param object
  494. var paramString = this.buildParamString();
  495. var httpSuccessString = this.settings.http_success.join(",");
  496. // Build the parameter string
  497. return ["movieName=", encodeURIComponent(this.movieName),
  498. "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
  499. "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
  500. "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
  501. "&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
  502. "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
  503. "&amp;params=", encodeURIComponent(paramString),
  504. "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
  505. "&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
  506. "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
  507. "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
  508. "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
  509. "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
  510. "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
  511. "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
  512. "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
  513. "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
  514. "&amp;buttonText=", encodeURIComponent(this.settings.button_text),
  515. "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
  516. "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
  517. "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
  518. "&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
  519. "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
  520. "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
  521. ].join("");
  522. };
  523. // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
  524. // The element is cached after the first lookup
  525. SWFUpload.prototype.getMovieElement = function () {
  526. if (this.movieElement == undefined) {
  527. this.movieElement = document.getElementById(this.movieName);
  528. }
  529. if (this.movieElement === null) {
  530. throw "Could not find Flash element";
  531. }
  532. return this.movieElement;
  533. };
  534. // Private: buildParamString takes the name/value pairs in the post_params setting object
  535. // and joins them up in to a string formatted "name=value&amp;name=value"
  536. SWFUpload.prototype.buildParamString = function () {
  537. var postParams = this.settings.post_params;
  538. var paramStringPairs = [];
  539. if (typeof(postParams) === "object") {
  540. for (var name in postParams) {
  541. if (postParams.hasOwnProperty(name)) {
  542. paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
  543. }
  544. }
  545. }
  546. return paramStringPairs.join("&amp;");
  547. };
  548. // Public: Used to remove a SWFUpload instance from the page. This method strives to remove
  549. // all references to the SWF, and other objects so memory is properly freed.
  550. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
  551. // Credits: Major improvements provided by steffen
  552. SWFUpload.prototype.destroy = function () {
  553. try {
  554. // Make sure Flash is done before we try to remove it
  555. this.cancelUpload(null, false);
  556. // Remove the SWFUpload DOM nodes
  557. var movieElement = null;
  558. movieElement = this.getMovieElement();
  559. if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  560. // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
  561. for (var i in movieElement) {
  562. try {
  563. if (typeof(movieElement[i]) === "function") {
  564. movieElement[i] = null;
  565. }
  566. } catch (ex1) {}
  567. }
  568. // Remove the Movie Element from the page
  569. try {
  570. movieElement.parentNode.removeChild(movieElement);
  571. } catch (ex) {}
  572. }
  573. // Remove IE form fix reference
  574. window[this.movieName] = null;
  575. // Destroy other references
  576. SWFUpload.instances[this.movieName] = null;
  577. delete SWFUpload.instances[this.movieName];
  578. this.movieElement = null;
  579. this.settings = null;
  580. this.customSettings = null;
  581. this.eventQueue = null;
  582. this.movieName = null;
  583. return true;
  584. } catch (ex2) {
  585. return false;
  586. }
  587. };
  588. // Public: displayDebugInfo prints out settings and configuration
  589. // information about this SWFUpload instance.
  590. // This function (and any references to it) can be deleted when placing
  591. // SWFUpload in production.
  592. SWFUpload.prototype.displayDebugInfo = function () {
  593. this.debug(
  594. [
  595. "---SWFUpload Instance Info---\n",
  596. "Version: ", SWFUpload.version, "\n",
  597. "Movie Name: ", this.movieName, "\n",
  598. "Settings:\n",
  599. "\t", "upload_url: ", this.settings.upload_url, "\n",
  600. "\t", "flash_url: ", this.settings.flash_url, "\n",
  601. "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
  602. "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
  603. "\t", "http_success: ", this.settings.http_success.join(", "), "\n",
  604. "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n",
  605. "\t", "file_post_name: ", this.settings.file_post_name, "\n",
  606. "\t", "post_params: ", this.settings.post_params.toString(), "\n",
  607. "\t", "file_types: ", this.settings.file_types, "\n",
  608. "\t", "file_types_description: ", this.settings.file_types_description, "\n",
  609. "\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
  610. "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
  611. "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
  612. "\t", "debug: ", this.settings.debug.toString(), "\n",
  613. "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
  614. "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
  615. "\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
  616. "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
  617. "\t", "button_width: ", this.settings.button_width.toString(), "\n",
  618. "\t", "button_height: ", this.settings.button_height.toString(), "\n",
  619. "\t", "button_text: ", this.settings.button_text.toString(), "\n",
  620. "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
  621. "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
  622. "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
  623. "\t", "button_action: ", this.settings.button_action.toString(), "\n",
  624. "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
  625. "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
  626. "Event Handlers:\n",
  627. "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
  628. "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
  629. "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
  630. "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
  631. "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
  632. "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
  633. "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
  634. "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
  635. "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
  636. "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n"
  637. ].join("")
  638. );
  639. };
  640. /* Note: addSetting and getSetting are no longer used by SWFUpload but are included
  641. the maintain v2 API compatibility
  642. */
  643. // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
  644. SWFUpload.prototype.addSetting = function (name, value, default_value) {
  645. if (value == undefined) {
  646. return (this.settings[name] = default_value);
  647. } else {
  648. return (this.settings[name] = value);
  649. }
  650. };
  651. // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
  652. SWFUpload.prototype.getSetting = function (name) {
  653. if (this.settings[name] != undefined) {
  654. return this.settings[name];
  655. }
  656. return "";
  657. };
  658. // Private: callFlash handles function calls made to the Flash element.
  659. // Calls are made with a setTimeout for some functions to work around
  660. // bugs in the ExternalInterface library.
  661. SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
  662. argumentArray = argumentArray || [];
  663. var movieElement = this.getMovieElement();
  664. var returnValue, returnString;
  665. // Flash's method if calling ExternalInterface methods (code adapted from MooTools).
  666. try {
  667. returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
  668. returnValue = eval(returnString);
  669. } catch (ex) {
  670. throw "Call to " + functionName + " failed";
  671. }
  672. // Unescape file post param values
  673. if (returnValue != undefined && typeof returnValue.post === "object") {
  674. returnValue = this.unescapeFilePostParams(returnValue);
  675. }
  676. return returnValue;
  677. };
  678. /* *****************************
  679. -- Flash control methods --
  680. Your UI should use these
  681. to operate SWFUpload
  682. ***************************** */
  683. // WARNING: this function does not work in Flash Player 10
  684. // Public: selectFile causes a File Selection Dialog window to appear. This
  685. // dialog only allows 1 file to be selected.
  686. SWFUpload.prototype.selectFile = function () {
  687. this.callFlash("SelectFile");
  688. };
  689. // WARNING: this function does not work in Flash Player 10
  690. // Public: selectFiles causes a File Selection Dialog window to appear/ This
  691. // dialog allows the user to select any number of files
  692. // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
  693. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around
  694. // for this bug.
  695. SWFUpload.prototype.selectFiles = function () {
  696. this.callFlash("SelectFiles");
  697. };
  698. // Public: startUpload starts uploading the first file in the queue unless
  699. // the optional parameter 'fileID' specifies the ID
  700. SWFUpload.prototype.startUpload = function (fileID) {
  701. this.callFlash("StartUpload", [fileID]);
  702. };
  703. // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index.
  704. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
  705. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
  706. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
  707. if (triggerErrorEvent !== false) {
  708. triggerErrorEvent = true;
  709. }
  710. this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
  711. };
  712. // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
  713. // If nothing is currently uploading then nothing happens.
  714. SWFUpload.prototype.stopUpload = function () {
  715. this.callFlash("StopUpload");
  716. };
  717. /* ************************
  718. * Settings methods
  719. * These methods change the SWFUpload settings.
  720. * SWFUpload settings should not be changed directly on the settings object
  721. * since many of the settings need to be passed to Flash in order to take
  722. * effect.
  723. * *********************** */
  724. // Public: getStats gets the file statistics object.
  725. SWFUpload.prototype.getStats = function () {
  726. return this.callFlash("GetStats");
  727. };
  728. // Public: setStats changes the SWFUpload statistics. You shouldn't need to
  729. // change the statistics but you can. Changing the statistics does not
  730. // affect SWFUpload accept for the successful_uploads count which is used
  731. // by the upload_limit setting to determine how many files the user may upload.
  732. SWFUpload.prototype.setStats = function (statsObject) {
  733. this.callFlash("SetStats", [statsObject]);
  734. };
  735. // Public: getFile retrieves a File object by ID or Index. If the file is
  736. // not found then 'null' is returned.
  737. SWFUpload.prototype.getFile = function (fileID) {
  738. if (typeof(fileID) === "number") {
  739. return this.callFlash("GetFileByIndex", [fileID]);
  740. } else {
  741. return this.callFlash("GetFile", [fileID]);
  742. }
  743. };
  744. // Public: addFileParam sets a name/value pair that will be posted with the
  745. // file specified by the Files ID. If the name already exists then the
  746. // exiting value will be overwritten.
  747. SWFUpload.prototype.addFileParam = function (fileID, name, value) {
  748. return this.callFlash("AddFileParam", [fileID, name, value]);
  749. };
  750. // Public: removeFileParam removes a previously set (by addFileParam) name/value
  751. // pair from the specified file.
  752. SWFUpload.prototype.removeFileParam = function (fileID, name) {
  753. this.callFlash("RemoveFileParam", [fileID, name]);
  754. };
  755. // Public: setUploadUrl changes the upload_url setting.
  756. SWFUpload.prototype.setUploadURL = function (url) {
  757. this.settings.upload_url = url.toString();
  758. this.callFlash("SetUploadURL", [url]);
  759. };
  760. // Public: setPostParams changes the post_params setting
  761. SWFUpload.prototype.setPostParams = function (paramsObject) {
  762. this.settings.post_params = paramsObject;
  763. this.callFlash("SetPostParams", [paramsObject]);
  764. };
  765. // Public: addPostParam adds post name/value pair. Each name can have only one value.
  766. SWFUpload.prototype.addPostParam = function (name, value) {
  767. this.settings.post_params[name] = value;
  768. this.callFlash("SetPostParams", [this.settings.post_params]);
  769. };
  770. // Public: removePostParam deletes post name/value pair.
  771. SWFUpload.prototype.removePostParam = function (name) {
  772. delete this.settings.post_params[name];
  773. this.callFlash("SetPostParams", [this.settings.post_params]);
  774. };
  775. // Public: setFileTypes changes the file_types setting and the file_types_description setting
  776. SWFUpload.prototype.setFileTypes = function (types, description) {
  777. this.settings.file_types = types;
  778. this.settings.file_types_description = description;
  779. this.callFlash("SetFileTypes", [types, description]);
  780. };
  781. // Public: setFileSizeLimit changes the file_size_limit setting
  782. SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
  783. this.settings.file_size_limit = fileSizeLimit;
  784. this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
  785. };
  786. // Public: setFileUploadLimit changes the file_upload_limit setting
  787. SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
  788. this.settings.file_upload_limit = fileUploadLimit;
  789. this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
  790. };
  791. // Public: setFileQueueLimit changes the file_queue_limit setting
  792. SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
  793. this.settings.file_queue_limit = fileQueueLimit;
  794. this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
  795. };
  796. // Public: setFilePostName changes the file_post_name setting
  797. SWFUpload.prototype.setFilePostName = function (filePostName) {
  798. this.settings.file_post_name = filePostName;
  799. this.callFlash("SetFilePostName", [filePostName]);
  800. };
  801. // Public: setUseQueryString changes the use_query_string setting
  802. SWFUpload.prototype.setUseQueryString = function (useQueryString) {
  803. this.settings.use_query_string = useQueryString;
  804. this.callFlash("SetUseQueryString", [useQueryString]);
  805. };
  806. // Public: setRequeueOnError changes the requeue_on_error setting
  807. SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
  808. this.settings.requeue_on_error = requeueOnError;
  809. this.callFlash("SetRequeueOnError", [requeueOnError]);
  810. };
  811. // Public: setHTTPSuccess changes the http_success setting
  812. SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
  813. if (typeof http_status_codes === "string") {
  814. http_status_codes = http_status_codes.replace(" ", "").split(",");
  815. }
  816. this.settings.http_success = http_status_codes;
  817. this.callFlash("SetHTTPSuccess", [http_status_codes]);
  818. };
  819. // Public: setHTTPSuccess changes the http_success setting
  820. SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
  821. this.settings.assume_success_timeout = timeout_seconds;
  822. this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
  823. };
  824. // Public: setDebugEnabled changes the debug_enabled setting
  825. SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
  826. this.settings.debug_enabled = debugEnabled;
  827. this.callFlash("SetDebugEnabled", [debugEnabled]);
  828. };
  829. // Public: setButtonImageURL loads a button image sprite
  830. SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
  831. if (buttonImageURL == undefined) {
  832. buttonImageURL = "";
  833. }
  834. this.settings.button_image_url = buttonImageURL;
  835. this.callFlash("SetButtonImageURL", [buttonImageURL]);
  836. };
  837. // Public: setButtonDimensions resizes the Flash Movie and button
  838. SWFUpload.prototype.setButtonDimensions = function (width, height) {
  839. this.settings.button_width = width;
  840. this.settings.button_height = height;
  841. var movie = this.getMovieElement();
  842. if (movie != undefined) {
  843. movie.style.width = width + "px";
  844. movie.style.height = height + "px";
  845. }
  846. this.callFlash("SetButtonDimensions", [width, height]);
  847. };
  848. // Public: setButtonText Changes the text overlaid on the button
  849. SWFUpload.prototype.setButtonText = function (html) {
  850. this.settings.button_text = html;
  851. this.callFlash("SetButtonText", [html]);
  852. };
  853. // Public: setButtonTextPadding changes the top and left padding of the text overlay
  854. SWFUpload.prototype.setButtonTextPadding = function (left, top) {
  855. this.settings.button_text_top_padding = top;
  856. this.settings.button_text_left_padding = left;
  857. this.callFlash("SetButtonTextPadding", [left, top]);
  858. };
  859. // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
  860. SWFUpload.prototype.setButtonTextStyle = function (css) {
  861. this.settings.button_text_style = css;
  862. this.callFlash("SetButtonTextStyle", [css]);
  863. };
  864. // Public: setButtonDisabled disables/enables the button
  865. SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
  866. this.settings.button_disabled = isDisabled;
  867. this.callFlash("SetButtonDisabled", [isDisabled]);
  868. };
  869. // Public: setButtonAction sets the action that occurs when the button is clicked
  870. SWFUpload.prototype.setButtonAction = function (buttonAction) {
  871. this.settings.button_action = buttonAction;
  872. this.callFlash("SetButtonAction", [buttonAction]);
  873. };
  874. // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
  875. SWFUpload.prototype.setButtonCursor = function (cursor) {
  876. this.settings.button_cursor = cursor;
  877. this.callFlash("SetButtonCursor", [cursor]);
  878. };
  879. /* *******************************
  880. Flash Event Interfaces
  881. These functions are used by Flash to trigger the various
  882. events.
  883. All these functions a Private.
  884. Because the ExternalInterface library is buggy the event calls
  885. are added to a queue and the queue then executed by a setTimeout.
  886. This ensures that events are executed in a determinate order and that
  887. the ExternalInterface bugs are avoided.
  888. ******************************* */
  889. SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
  890. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  891. if (argumentArray == undefined) {
  892. argumentArray = [];
  893. } else if (!(argumentArray instanceof Array)) {
  894. argumentArray = [argumentArray];
  895. }
  896. var self = this;
  897. if (typeof this.settings[handlerName] === "function") {
  898. // Queue the event
  899. this.eventQueue.push(function () {
  900. this.settings[handlerName].apply(this, argumentArray);
  901. });
  902. // Execute the next queued event
  903. setTimeout(function () {
  904. self.executeNextEvent();
  905. }, 0);
  906. } else if (this.settings[handlerName] !== null) {
  907. throw "Event handler " + handlerName + " is unknown or is not a function";
  908. }
  909. };
  910. // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
  911. // we must queue them in order to garentee that they are executed in order.
  912. SWFUpload.prototype.executeNextEvent = function () {
  913. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  914. var f = this.eventQueue ? this.eventQueue.shift() : null;
  915. if (typeof(f) === "function") {
  916. f.apply(this);
  917. }
  918. };
  919. // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
  920. // properties that contain characters that are not valid for JavaScript identifiers. To work around this
  921. // the Flash Component escapes the parameter names and we must unescape again before passing them along.
  922. SWFUpload.prototype.unescapeFilePostParams = function (file) {
  923. var reg = /[$]([0-9a-f]{4})/i;
  924. var unescapedPost = {};
  925. var uk;
  926. if (file != undefined) {
  927. for (var k in file.post) {
  928. if (file.post.hasOwnProperty(k)) {
  929. uk = k;
  930. var match;
  931. while ((match = reg.exec(uk)) !== null) {
  932. uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
  933. }
  934. unescapedPost[uk] = file.post[k];
  935. }
  936. }
  937. file.post = unescapedPost;
  938. }
  939. return file;
  940. };
  941. // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
  942. SWFUpload.prototype.testExternalInterface = function () {
  943. try {
  944. return this.callFlash("TestExternalInterface");
  945. } catch (ex) {
  946. return false;
  947. }
  948. };
  949. // Private: This event is called by Flash when it has finished loading. Don't modify this.
  950. // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
  951. SWFUpload.prototype.flashReady = function () {
  952. // Check that the movie element is loaded correctly with its ExternalInterface methods defined
  953. var movieElement = this.getMovieElement();
  954. if (!movieElement) {
  955. this.debug("Flash called back ready but the flash movie can't be found.");
  956. return;
  957. }
  958. this.cleanUp(movieElement);
  959. this.queueEvent("swfupload_loaded_handler");
  960. };
  961. // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
  962. // This function is called by Flash each time the ExternalInterface functions are created.
  963. SWFUpload.prototype.cleanUp = function (movieElement) {
  964. // Pro-actively unhook all the Flash functions
  965. try {
  966. if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  967. this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
  968. for (var key in movieElement) {
  969. try {
  970. if (typeof(movieElement[key]) === "function") {
  971. movieElement[key] = null;
  972. }
  973. } catch (ex) {
  974. }
  975. }
  976. }
  977. } catch (ex1) {
  978. }
  979. // Fix Flashes own cleanup code so if the SWFMovie was removed from the page
  980. // it doesn't display errors.
  981. window["__flash__removeCallback"] = function (instance, name) {
  982. try {
  983. if (instance) {
  984. instance[name] = null;
  985. }
  986. } catch (flashEx) {
  987. }
  988. };
  989. };
  990. /* This is a chance to do something before the browse window opens */
  991. SWFUpload.prototype.fileDialogStart = function () {
  992. this.queueEvent("file_dialog_start_handler");
  993. };
  994. /* Called when a file is successfully added to the queue. */
  995. SWFUpload.prototype.fileQueued = function (file) {
  996. file = this.unescapeFilePostParams(file);
  997. this.queueEvent("file_queued_handler", file);
  998. };
  999. /* Handle errors that occur when an attempt to queue a file fails. */
  1000. SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
  1001. file = this.unescapeFilePostParams(file);
  1002. this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
  1003. };
  1004. /* Called after the file dialog has closed and the selected files have been queued.
  1005. You could call startUpload here if you want the queued files to begin uploading immediately. */
  1006. SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
  1007. this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
  1008. };
  1009. SWFUpload.prototype.uploadStart = function (file) {
  1010. file = this.unescapeFilePostParams(file);
  1011. this.queueEvent("return_upload_start_handler", file);
  1012. };
  1013. SWFUpload.prototype.returnUploadStart = function (file) {
  1014. var returnValue;
  1015. if (typeof this.settings.upload_start_handler === "function") {
  1016. file = this.unescapeFilePostParams(file);
  1017. returnValue = this.settings.upload_start_handler.call(this, file);
  1018. } else if (this.settings.upload_start_handler != undefined) {
  1019. throw "upload_start_handler must be a function";
  1020. }
  1021. // Convert undefined to true so if nothing is returned from the upload_start_handler it is
  1022. // interpretted as 'true'.
  1023. if (returnValue === undefined) {
  1024. returnValue = true;
  1025. }
  1026. returnValue = !!returnValue;
  1027. this.callFlash("ReturnUploadStart", [returnValue]);
  1028. };
  1029. SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
  1030. file = this.unescapeFilePostParams(file);
  1031. this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
  1032. };
  1033. SWFUpload.prototype.uploadError = function (file, errorCode, message) {
  1034. file = this.unescapeFilePostParams(file);
  1035. this.queueEvent("upload_error_handler", [file, errorCode, message]);
  1036. };
  1037. SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
  1038. file = this.unescapeFilePostParams(file);
  1039. this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
  1040. };
  1041. SWFUpload.prototype.uploadComplete = function (file) {
  1042. file = this.unescapeFilePostParams(file);
  1043. this.queueEvent("upload_complete_handler", file);
  1044. };
  1045. /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
  1046. internal debug console. You can override this event and have messages written where you want. */
  1047. SWFUpload.prototype.debug = function (message) {
  1048. this.queueEvent("debug_handler", message);
  1049. };
  1050. /* **********************************
  1051. Debug Console
  1052. The debug console is a self contained, in page location
  1053. for debug message to be sent. The Debug Console adds
  1054. itself to the body if necessary.
  1055. The console is automatically scrolled as messages appear.
  1056. If you are using your own debug handler or when you deploy to production and
  1057. have debug disabled you can remove these functions to reduce the file size
  1058. and complexity.
  1059. ********************************** */
  1060. // Private: debugMessage is the default debug_handler. If you want to print debug messages
  1061. // call the debug() function. When overriding the function your own function should
  1062. // check to see if the debug setting is true before outputting debug information.
  1063. SWFUpload.prototype.debugMessage = function (message) {
  1064. if (this.settings.debug) {
  1065. var exceptionMessage, exceptionValues = [];
  1066. // Check for an exception object and print it nicely
  1067. if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
  1068. for (var key in message) {
  1069. if (message.hasOwnProperty(key)) {
  1070. exceptionValues.push(key + ": " + message[key]);
  1071. }
  1072. }
  1073. exceptionMessage = exceptionValues.join("\n") || "";
  1074. exceptionValues = exceptionMessage.split("\n");
  1075. exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
  1076. SWFUpload.Console.writeLine(exceptionMessage);
  1077. } else {
  1078. SWFUpload.Console.writeLine(message);
  1079. }
  1080. }
  1081. };
  1082. SWFUpload.Console = {};
  1083. SWFUpload.Console.writeLine = function (message) {
  1084. var console, documentForm;
  1085. try {
  1086. console = document.getElementById("SWFUpload_Console");
  1087. if (!console) {
  1088. documentForm = document.createElement("form");
  1089. document.getElementsByTagName("body")[0].appendChild(documentForm);
  1090. console = document.createElement("textarea");
  1091. console.id = "SWFUpload_Console";
  1092. console.style.fontFamily = "monospace";
  1093. console.setAttribute("wrap", "off");
  1094. console.wrap = "off";
  1095. console.style.overflow = "auto";
  1096. console.style.width = "700px";
  1097. console.style.height = "350px";
  1098. console.style.margin = "5px";
  1099. documentForm.appendChild(console);
  1100. }
  1101. console.value += message + "\n";
  1102. console.scrollTop = console.scrollHeight - console.clientHeight;
  1103. } catch (ex) {
  1104. alert("Exception: " + ex.name + " Message: " + ex.message);
  1105. }
  1106. };
  1107. })();
  1108. (function() {
  1109. /*
  1110. Queue Plug-in
  1111. Features:
  1112. *Adds a cancelQueue() method for cancelling the entire queue.
  1113. *All queued files are uploaded when startUpload() is called.
  1114. *If false is returned from uploadComplete then the queue upload is stopped.
  1115. If false is not returned (strict comparison) then the queue upload is continued.
  1116. *Adds a QueueComplete event that is fired when all the queued files have finished uploading.
  1117. Set the event handler with the queue_complete_handler setting.
  1118. */
  1119. if (typeof(SWFUpload) === "function") {
  1120. SWFUpload.queue = {};
  1121. SWFUpload.prototype.initSettings = (function (oldInitSettings) {
  1122. return function () {
  1123. if (typeof(oldInitSettings) === "function") {
  1124. oldInitSettings.call(this);
  1125. }
  1126. this.queueSettings = {};
  1127. this.queueSettings.queue_cancelled_flag = false;
  1128. this.queueSettings.queue_upload_count = 0;
  1129. this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
  1130. this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
  1131. this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
  1132. this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
  1133. this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
  1134. };
  1135. })(SWFUpload.prototype.initSettings);
  1136. SWFUpload.prototype.startUpload = function (fileID) {
  1137. this.queueSettings.queue_cancelled_flag = false;
  1138. this.callFlash("StartUpload", [fileID]);
  1139. };
  1140. SWFUpload.prototype.cancelQueue = function () {
  1141. this.queueSettings.queue_cancelled_flag = true;
  1142. this.stopUpload();
  1143. var stats = this.getStats();
  1144. while (stats.files_queued > 0) {
  1145. this.cancelUpload();
  1146. stats = this.getStats();
  1147. }
  1148. };
  1149. SWFUpload.queue.uploadStartHandler = function (file) {
  1150. var returnValue;
  1151. if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
  1152. returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
  1153. }
  1154. // To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
  1155. returnValue = (returnValue === false) ? false : true;
  1156. this.queueSettings.queue_cancelled_flag = !returnValue;
  1157. return returnValue;
  1158. };
  1159. SWFUpload.queue.uploadCompleteHandler = function (file) {
  1160. var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
  1161. var continueUpload;
  1162. if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
  1163. this.queueSettings.queue_upload_count++;
  1164. }
  1165. if (typeof(user_upload_complete_handler) === "function") {
  1166. continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
  1167. } else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
  1168. // If the file was stopped and re-queued don't restart the upload
  1169. continueUpload = false;
  1170. } else {
  1171. continueUpload = true;
  1172. }
  1173. if (continueUpload) {
  1174. var stats = this.getStats();
  1175. if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
  1176. this.startUpload();
  1177. } else if (this.queueSettings.queue_cancelled_flag === false) {
  1178. this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
  1179. this.queueSettings.queue_upload_count = 0;
  1180. } else {
  1181. this.queueSettings.queue_cancelled_flag = false;
  1182. this.queueSettings.queue_upload_count = 0;
  1183. }
  1184. }
  1185. };
  1186. }
  1187. })();