image.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. /**
  2. * User: Jinqn
  3. * Date: 14-04-08
  4. * Time: 下午16:34
  5. * 上传图片对话框逻辑代码,包括tab: 远程图片/上传图片/在线图片/搜索图片
  6. */
  7. (function () {
  8. var remoteImage,
  9. uploadImage,
  10. onlineImage,
  11. searchImage;
  12. window.onload = function () {
  13. initTabs();
  14. initAlign();
  15. initButtons();
  16. };
  17. /* 初始化tab标签 */
  18. function initTabs() {
  19. var tabs = $G('tabhead').children;
  20. for (var i = 0; i < tabs.length; i++) {
  21. domUtils.on(tabs[i], "click", function (e) {
  22. var target = e.target || e.srcElement;
  23. setTabFocus(target.getAttribute('data-content-id'));
  24. });
  25. }
  26. var img = editor.selection.getRange().getClosedNode();
  27. if (img && img.tagName && img.tagName.toLowerCase() == 'img') {
  28. setTabFocus('remote');
  29. } else {
  30. setTabFocus('upload');
  31. }
  32. }
  33. /* 初始化tabbody */
  34. function setTabFocus(id) {
  35. if (!id) return;
  36. var i, bodyId, tabs = $G('tabhead').children;
  37. for (i = 0; i < tabs.length; i++) {
  38. bodyId = tabs[i].getAttribute('data-content-id');
  39. if (bodyId == id) {
  40. domUtils.addClass(tabs[i], 'focus');
  41. domUtils.addClass($G(bodyId), 'focus');
  42. } else {
  43. domUtils.removeClasses(tabs[i], 'focus');
  44. domUtils.removeClasses($G(bodyId), 'focus');
  45. }
  46. }
  47. switch (id) {
  48. case 'remote':
  49. remoteImage = remoteImage || new RemoteImage();
  50. break;
  51. case 'upload':
  52. setAlign(editor.getOpt('imageInsertAlign'));
  53. uploadImage = uploadImage || new UploadImage('queueList');
  54. break;
  55. case 'online':
  56. setAlign(editor.getOpt('imageManagerInsertAlign'));
  57. // onlineImage = onlineImage || new OnlineImage('imageList');
  58. // onlineImage.reset();
  59. let Fast = editor.getOpt("uploadService")(this, editor).Fast();
  60. dialog.close(false);
  61. Fast.api.open("general/attachment/select?element_id=&multiple=true&mimetype=image/*", "选择", {
  62. callback: function (data) {
  63. var urlArr = data.url.split(/\,/);
  64. urlArr.forEach(function (item, index) {
  65. var url = Fast.api.cdnurl(item, true);
  66. editor.execCommand('insertimage', {
  67. src: url,
  68. _src: url
  69. });
  70. });
  71. }
  72. });
  73. break;
  74. case 'search':
  75. setAlign(editor.getOpt('imageManagerInsertAlign'));
  76. searchImage = searchImage || new SearchImage();
  77. break;
  78. }
  79. }
  80. /* 初始化onok事件 */
  81. function initButtons() {
  82. dialog.onok = function () {
  83. var remote = false, list = [], id, tabs = $G('tabhead').children;
  84. for (var i = 0; i < tabs.length; i++) {
  85. if (domUtils.hasClass(tabs[i], 'focus')) {
  86. id = tabs[i].getAttribute('data-content-id');
  87. break;
  88. }
  89. }
  90. switch (id) {
  91. case 'remote':
  92. list = remoteImage.getInsertList();
  93. break;
  94. case 'upload':
  95. list = uploadImage.getInsertList();
  96. var count = uploadImage.getQueueCount();
  97. if (count) {
  98. $('.info', '#queueList').html('<span style="color:red;">' + '还有2个未上传文件'.replace(/[\d]/, count) + '</span>');
  99. return false;
  100. }
  101. break;
  102. case 'online':
  103. list = onlineImage.getInsertList();
  104. break;
  105. case 'search':
  106. list = searchImage.getInsertList();
  107. remote = true;
  108. break;
  109. }
  110. if (list) {
  111. editor.execCommand('insertimage', list);
  112. remote && editor.fireEvent("catchRemoteImage");
  113. }
  114. };
  115. }
  116. /* 初始化对其方式的点击事件 */
  117. function initAlign() {
  118. /* 点击align图标 */
  119. domUtils.on($G("alignIcon"), 'click', function (e) {
  120. var target = e.target || e.srcElement;
  121. if (target.className && target.className.indexOf('-align') != -1) {
  122. setAlign(target.getAttribute('data-align'));
  123. }
  124. });
  125. }
  126. /* 设置对齐方式 */
  127. function setAlign(align) {
  128. align = align || 'none';
  129. var aligns = $G("alignIcon").children;
  130. for (i = 0; i < aligns.length; i++) {
  131. if (aligns[i].getAttribute('data-align') == align) {
  132. domUtils.addClass(aligns[i], 'focus');
  133. $G("align").value = aligns[i].getAttribute('data-align');
  134. } else {
  135. domUtils.removeClasses(aligns[i], 'focus');
  136. }
  137. }
  138. }
  139. /* 获取对齐方式 */
  140. function getAlign() {
  141. var align = $G("align").value || 'none';
  142. return align == 'none' ? '' : align;
  143. }
  144. /* 在线图片 */
  145. function RemoteImage(target) {
  146. this.container = utils.isString(target) ? document.getElementById(target) : target;
  147. this.init();
  148. }
  149. RemoteImage.prototype = {
  150. init: function () {
  151. this.initContainer();
  152. this.initEvents();
  153. },
  154. initContainer: function () {
  155. this.dom = {
  156. 'url': $G('url'),
  157. 'width': $G('width'),
  158. 'height': $G('height'),
  159. 'border': $G('border'),
  160. 'vhSpace': $G('vhSpace'),
  161. 'title': $G('title'),
  162. 'align': $G('align')
  163. };
  164. var img = editor.selection.getRange().getClosedNode();
  165. if (img) {
  166. this.setImage(img);
  167. }
  168. },
  169. initEvents: function () {
  170. var _this = this,
  171. locker = $G('lock');
  172. /* 改变url */
  173. domUtils.on($G("url"), 'keyup', updatePreview);
  174. domUtils.on($G("border"), 'keyup', updatePreview);
  175. domUtils.on($G("title"), 'keyup', updatePreview);
  176. domUtils.on($G("width"), 'keyup', function () {
  177. if (locker.checked) {
  178. var proportion = locker.getAttribute('data-proportion');
  179. $G('height').value = Math.round(this.value / proportion);
  180. } else {
  181. _this.updateLocker();
  182. }
  183. updatePreview();
  184. });
  185. domUtils.on($G("height"), 'keyup', function () {
  186. if (locker.checked) {
  187. var proportion = locker.getAttribute('data-proportion');
  188. $G('width').value = Math.round(this.value * proportion);
  189. } else {
  190. _this.updateLocker();
  191. }
  192. updatePreview();
  193. });
  194. domUtils.on($G("lock"), 'change', function () {
  195. var proportion = parseInt($G("width").value) / parseInt($G("height").value);
  196. locker.setAttribute('data-proportion', proportion);
  197. });
  198. function updatePreview() {
  199. _this.setPreview();
  200. }
  201. },
  202. updateLocker: function () {
  203. var width = $G('width').value,
  204. height = $G('height').value,
  205. locker = $G('lock');
  206. if (width && height && width == parseInt(width) && height == parseInt(height)) {
  207. locker.disabled = false;
  208. locker.title = '';
  209. } else {
  210. locker.checked = false;
  211. locker.disabled = 'disabled';
  212. locker.title = lang.remoteLockError;
  213. }
  214. },
  215. setImage: function (img) {
  216. /* 不是正常的图片 */
  217. if (!img.tagName || img.tagName.toLowerCase() != 'img' && !img.getAttribute("src") || !img.src) return;
  218. var wordImgFlag = img.getAttribute("word_img"),
  219. src = wordImgFlag ? wordImgFlag.replace("&amp;", "&") : (img.getAttribute('_src') || img.getAttribute("src", 2).replace("&amp;", "&")),
  220. align = editor.queryCommandValue("imageFloat");
  221. /* 防止onchange事件循环调用 */
  222. if (src !== $G("url").value) $G("url").value = src;
  223. if (src) {
  224. /* 设置表单内容 */
  225. $G("width").value = img.width || '';
  226. $G("height").value = img.height || '';
  227. $G("border").value = img.getAttribute("border") || '0';
  228. $G("vhSpace").value = img.getAttribute("vspace") || '0';
  229. $G("title").value = img.title || img.alt || '';
  230. setAlign(align);
  231. this.setPreview();
  232. this.updateLocker();
  233. }
  234. },
  235. getData: function () {
  236. var data = {};
  237. for (var k in this.dom) {
  238. data[k] = this.dom[k].value;
  239. }
  240. return data;
  241. },
  242. setPreview: function () {
  243. var url = $G('url').value,
  244. ow = $G('width').value,
  245. oh = $G('height').value,
  246. border = $G('border').value,
  247. title = $G('title').value,
  248. preview = $G('preview'),
  249. width,
  250. height;
  251. width = ((!ow || !oh) ? preview.offsetWidth : Math.min(ow, preview.offsetWidth));
  252. width = width + (border * 2) > preview.offsetWidth ? width : (preview.offsetWidth - (border * 2));
  253. height = (!ow || !oh) ? '' : width * oh / ow;
  254. if (url) {
  255. preview.innerHTML = '<img src="' + url + '" width="' + width + '" height="' + height + '" border="' + border + 'px solid #000" title="' + title + '" />';
  256. }
  257. },
  258. getInsertList: function () {
  259. var data = this.getData();
  260. if (data['url']) {
  261. return [{
  262. src: data['url'],
  263. _src: data['url'],
  264. width: data['width'] || '',
  265. height: data['height'] || '',
  266. border: data['border'] || '',
  267. floatStyle: data['align'] || '',
  268. vspace: data['vhSpace'] || '',
  269. alt: data['title'] || '',
  270. style: "width:" + data['width'] + "px;height:" + data['height'] + "px;"
  271. }];
  272. } else {
  273. return [];
  274. }
  275. }
  276. };
  277. /* 上传图片 */
  278. function UploadImage(target) {
  279. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  280. this.init();
  281. }
  282. UploadImage.prototype = {
  283. init: function () {
  284. this.imageList = [];
  285. this.initContainer();
  286. this.initUploader();
  287. },
  288. initContainer: function () {
  289. this.$queue = this.$wrap.find('.filelist');
  290. },
  291. /* 初始化容器 */
  292. initUploader: function () {
  293. var _this = this,
  294. $ = jQuery, // just in case. Make sure it's not an other libaray.
  295. $wrap = _this.$wrap,
  296. // 图片容器
  297. $queue = $wrap.find('.filelist'),
  298. // 状态栏,包括进度和控制按钮
  299. $statusBar = $wrap.find('.statusBar'),
  300. // 文件总体选择信息。
  301. $info = $statusBar.find('.info'),
  302. // 上传按钮
  303. $upload = $wrap.find('.uploadBtn'),
  304. // 上传按钮
  305. $filePickerBtn = $wrap.find('.filePickerBtn'),
  306. // 上传按钮
  307. $filePickerBlock = $wrap.find('.filePickerBlock'),
  308. // 没选择文件之前的内容。
  309. $placeHolder = $wrap.find('.placeholder'),
  310. // 总体进度条
  311. $progress = $statusBar.find('.progress').hide(),
  312. // 添加的文件数量
  313. fileCount = 0,
  314. // 添加的文件总大小
  315. fileSize = 0,
  316. // 优化retina, 在retina下这个值是2
  317. ratio = window.devicePixelRatio || 1,
  318. // 缩略图大小
  319. thumbnailWidth = 113 * ratio,
  320. thumbnailHeight = 113 * ratio,
  321. // 可能有pedding, ready, uploading, confirm, done.
  322. state = '',
  323. // 所有文件的进度信息,key为file id
  324. percentages = {},
  325. supportTransition = (function () {
  326. var s = document.createElement('p').style,
  327. r = 'transition' in s ||
  328. 'WebkitTransition' in s ||
  329. 'MozTransition' in s ||
  330. 'msTransition' in s ||
  331. 'OTransition' in s;
  332. s = null;
  333. return r;
  334. })(),
  335. // WebUploader实例
  336. uploader,
  337. actionUrl = editor.getActionUrl(editor.getOpt('imageActionName')),
  338. acceptExtensions = (editor.getOpt('imageAllowFiles') || [".png", ".jpg", ".jpeg", ".gif", ".bmp"]).join('').replace(/\./g, ',').replace(/^[,]/, ''),
  339. imageMaxSize = editor.getOpt('imageMaxSize'),
  340. imageCompressBorder = editor.getOpt('imageCompressBorder'),
  341. filesArray = [];
  342. if (!WebUploader.Uploader.support()) {
  343. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  344. return;
  345. } else if (!editor.getOpt('imageActionName')) {
  346. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  347. return;
  348. }
  349. uploader = _this.uploader = WebUploader.create({
  350. pick: {
  351. id: '#filePickerReady',
  352. label: lang.uploadSelectFile
  353. },
  354. accept: {
  355. title: 'Images',
  356. extensions: acceptExtensions,
  357. mimeTypes: 'image/*'
  358. },
  359. swf: '../../third-party/webuploader/Uploader.swf',
  360. server: actionUrl,
  361. fileVal: editor.getOpt('imageFieldName'),
  362. duplicate: true,
  363. fileSingleSizeLimit: imageMaxSize, // 默认 2 M
  364. compress: editor.getOpt('imageCompressEnable') ? {
  365. width: imageCompressBorder,
  366. height: imageCompressBorder,
  367. // 图片质量,只有type为`image/jpeg`的时候才有效。
  368. quality: 90,
  369. // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  370. allowMagnify: false,
  371. // 是否允许裁剪。
  372. crop: false,
  373. // 是否保留头部meta信息。
  374. preserveHeaders: true
  375. } : false
  376. });
  377. uploader.addButton({
  378. id: '#filePickerBlock'
  379. });
  380. uploader.addButton({
  381. id: '#filePickerBtn',
  382. label: lang.uploadAddFile
  383. });
  384. setState('pedding');
  385. // 当有文件添加进来时执行,负责view的创建
  386. function addFile(file) {
  387. var $li = $('<li id="' + file.id + '">' +
  388. '<p class="title">' + file.name + '</p>' +
  389. '<p class="imgWrap"></p>' +
  390. '<p class="progress"><span></span></p>' +
  391. '</li>'),
  392. $btns = $('<div class="file-panel">' +
  393. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  394. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  395. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  396. $prgress = $li.find('p.progress span'),
  397. $wrap = $li.find('p.imgWrap'),
  398. $info = $('<p class="error"></p>').hide().appendTo($li),
  399. showError = function (code) {
  400. switch (code) {
  401. case 'exceed_size':
  402. text = lang.errorExceedSize;
  403. break;
  404. case 'interrupt':
  405. text = lang.errorInterrupt;
  406. break;
  407. case 'http':
  408. text = lang.errorHttp;
  409. break;
  410. case 'not_allow_type':
  411. text = lang.errorFileType;
  412. break;
  413. default:
  414. text = lang.errorUploadRetry;
  415. break;
  416. }
  417. $info.text(text).show();
  418. };
  419. if (file.getStatus() === 'invalid') {
  420. showError(file.statusText);
  421. } else {
  422. $wrap.text(lang.uploadPreview);
  423. if (browser.ie && browser.version <= 7) {
  424. $wrap.text(lang.uploadNoPreview);
  425. } else {
  426. uploader.makeThumb(file, function (error, src) {
  427. if (error || !src) {
  428. $wrap.text(lang.uploadNoPreview);
  429. } else {
  430. var $img = $('<img src="' + src + '">');
  431. $wrap.empty().append($img);
  432. $img.on('error', function () {
  433. $wrap.text(lang.uploadNoPreview);
  434. });
  435. }
  436. }, thumbnailWidth, thumbnailHeight);
  437. }
  438. percentages[file.id] = [file.size, 0];
  439. file.rotation = 0;
  440. /* 检查文件格式 */
  441. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  442. showError('not_allow_type');
  443. uploader.removeFile(file);
  444. }
  445. }
  446. file.on('statuschange', function (cur, prev) {
  447. if (prev === 'progress') {
  448. $prgress.hide().width(0);
  449. } else if (prev === 'queued') {
  450. $li.off('mouseenter mouseleave');
  451. $btns.remove();
  452. }
  453. // 成功
  454. if (cur === 'error' || cur === 'invalid') {
  455. showError(file.statusText);
  456. percentages[file.id][1] = 1;
  457. } else if (cur === 'interrupt') {
  458. showError('interrupt');
  459. } else if (cur === 'queued') {
  460. percentages[file.id][1] = 0;
  461. } else if (cur === 'progress') {
  462. $info.hide();
  463. $prgress.css('display', 'block');
  464. } else if (cur === 'complete') {
  465. }
  466. $li.removeClass('state-' + prev).addClass('state-' + cur);
  467. });
  468. $li.on('mouseenter', function () {
  469. $btns.stop().animate({ height: 30 });
  470. });
  471. $li.on('mouseleave', function () {
  472. $btns.stop().animate({ height: 0 });
  473. });
  474. $btns.on('click', 'span', function () {
  475. var index = $(this).index(),
  476. deg;
  477. switch (index) {
  478. case 0:
  479. uploader.removeFile(file);
  480. return;
  481. case 1:
  482. file.rotation += 90;
  483. break;
  484. case 2:
  485. file.rotation -= 90;
  486. break;
  487. }
  488. if (supportTransition) {
  489. deg = 'rotate(' + file.rotation + 'deg)';
  490. $wrap.css({
  491. '-webkit-transform': deg,
  492. '-mos-transform': deg,
  493. '-o-transform': deg,
  494. 'transform': deg
  495. });
  496. } else {
  497. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  498. }
  499. });
  500. $li.insertBefore($filePickerBlock);
  501. }
  502. // 负责view的销毁
  503. function removeFile(file) {
  504. var $li = $('#' + file.id);
  505. delete percentages[file.id];
  506. updateTotalProgress();
  507. $li.off().find('.file-panel').off().end().remove();
  508. }
  509. function updateTotalProgress() {
  510. var loaded = 0,
  511. total = 0,
  512. spans = $progress.children(),
  513. percent;
  514. $.each(percentages, function (k, v) {
  515. total += v[0];
  516. loaded += v[0] * v[1];
  517. });
  518. percent = total ? loaded / total : 0;
  519. spans.eq(0).text(Math.round(percent * 100) + '%');
  520. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  521. updateStatus();
  522. }
  523. function setState(val, files) {
  524. if (val != state) {
  525. var stats = uploader.getStats();
  526. $upload.removeClass('state-' + state);
  527. $upload.addClass('state-' + val);
  528. switch (val) {
  529. /* 未选择文件 */
  530. case 'pedding':
  531. $queue.addClass('element-invisible');
  532. $statusBar.addClass('element-invisible');
  533. $placeHolder.removeClass('element-invisible');
  534. $progress.hide(); $info.hide();
  535. uploader.refresh();
  536. break;
  537. /* 可以开始上传 */
  538. case 'ready':
  539. $placeHolder.addClass('element-invisible');
  540. $queue.removeClass('element-invisible');
  541. $statusBar.removeClass('element-invisible');
  542. $progress.hide(); $info.show();
  543. $upload.text(lang.uploadStart);
  544. uploader.refresh();
  545. break;
  546. /* 上传中 */
  547. case 'uploading':
  548. $progress.show(); $info.hide();
  549. $upload.text(lang.uploadPause);
  550. break;
  551. /* 暂停上传 */
  552. case 'paused':
  553. $progress.show(); $info.hide();
  554. $upload.text(lang.uploadContinue);
  555. break;
  556. case 'confirm':
  557. $progress.show(); $info.hide();
  558. $upload.text(lang.uploadStart);
  559. stats = uploader.getStats();
  560. if (stats.successNum && !stats.uploadFailNum) {
  561. setState('finish');
  562. return;
  563. }
  564. break;
  565. case 'finish':
  566. $progress.hide(); $info.show();
  567. if (stats.uploadFailNum) {
  568. $upload.text(lang.uploadRetry);
  569. } else {
  570. $upload.text(lang.uploadStart);
  571. }
  572. break;
  573. }
  574. state = val;
  575. updateStatus();
  576. }
  577. if (!_this.getQueueCount()) {
  578. $upload.addClass('disabled')
  579. } else {
  580. $upload.removeClass('disabled')
  581. }
  582. }
  583. function updateStatus() {
  584. var text = '', stats;
  585. if (state === 'ready') {
  586. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  587. } else if (state === 'confirm') {
  588. stats = uploader.getStats();
  589. if (stats.uploadFailNum) {
  590. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  591. }
  592. } else {
  593. stats = uploader.getStats();
  594. text = lang.updateStatusFinish.replace('_', fileCount).
  595. replace('_KB', WebUploader.formatSize(fileSize)).
  596. replace('_', stats.successNum);
  597. if (stats.uploadFailNum) {
  598. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  599. }
  600. }
  601. $info.html(text);
  602. }
  603. uploader.on('fileQueued', function (file) {
  604. fileCount++;
  605. fileSize += file.size;
  606. if (fileCount === 1) {
  607. $placeHolder.addClass('element-invisible');
  608. $statusBar.show();
  609. }
  610. addFile(file);
  611. filesArray.push(file);
  612. });
  613. uploader.on('fileDequeued', function (file) {
  614. if (file.ext && acceptExtensions.indexOf(file.ext.toLowerCase()) != -1 && file.size <= imageMaxSize) {
  615. fileCount--;
  616. fileSize -= file.size;
  617. }
  618. removeFile(file);
  619. updateTotalProgress();
  620. var k = filesArray.findIndex(function (v) {
  621. return v.id == file.id
  622. });
  623. filesArray.splice(k, 1);
  624. });
  625. uploader.on('filesQueued', function (file) {
  626. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  627. setState('ready');
  628. }
  629. updateTotalProgress();
  630. });
  631. uploader.on('all', function (type, files) {
  632. switch (type) {
  633. case 'uploadFinished':
  634. setState('confirm', files);
  635. break;
  636. case 'startUpload':
  637. /* 添加额外的GET参数 */
  638. var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '',
  639. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?' : '&') + 'encode=utf-8&' + params);
  640. uploader.option('server', url);
  641. setState('uploading', files);
  642. break;
  643. case 'stopUpload':
  644. setState('paused', files);
  645. break;
  646. }
  647. });
  648. uploader.on('uploadBeforeSend', function (file, data, header) {
  649. //这里可以通过data对象添加POST参数
  650. if (actionUrl.toLowerCase().indexOf('jsp') != -1) {
  651. header['X-Requested-With'] = 'XMLHttpRequest';
  652. }
  653. });
  654. uploader.on('uploadProgress', function (file, percentage) {
  655. var $li = $('#' + file.id),
  656. $percent = $li.find('.progress span');
  657. $percent.css('width', percentage * 100 + '%');
  658. percentages[file.id][1] = percentage;
  659. updateTotalProgress();
  660. });
  661. uploader.on('uploadSuccess', function (file, ret) {
  662. var $file = $('#' + file.id);
  663. try {
  664. var responseText = (ret._raw || ret),
  665. json = utils.str2json(responseText);
  666. if (json.state == 'SUCCESS') {
  667. // _this.imageList.push(json);
  668. _this.imageList[$file.index()] = json; //按选择文件排序
  669. $file.append('<span class="success"></span>');
  670. } else {
  671. $file.find('.error').text(json.state).show();
  672. }
  673. } catch (e) {
  674. $file.find('.error').text(lang.errorServerUpload).show();
  675. }
  676. });
  677. uploader.on('uploadError', function (file, code) {
  678. });
  679. uploader.on('error', function (code, file) {
  680. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  681. addFile(file);
  682. }
  683. });
  684. uploader.on('uploadComplete', function (file, ret) {
  685. });
  686. $upload.on('click', function () {
  687. if ($(this).hasClass('disabled')) {
  688. return false;
  689. }
  690. // if (state === 'ready') {
  691. // uploader.upload();
  692. // } else if (state === 'paused') {
  693. // uploader.upload();
  694. // } else if (state === 'uploading') {
  695. // uploader.stop();
  696. // }
  697. let uploadAction = editor.getOpt("uploadService")(_this, editor).Upload();
  698. let Fast = editor.getOpt("uploadService")(_this, editor).Fast();
  699. //替换上传方法
  700. var filesObj = filesArray;
  701. for (var i = 0; i < filesObj.length; i++) {
  702. (function (j) {
  703. var file = filesObj[j];
  704. var id = filesObj[j].id;
  705. var name = filesObj[j].name;
  706. uploadAction.api.send(file.source.source, function (data) {
  707. var pic = {
  708. url: Fast.api.cdnurl(data.url, true),
  709. state: "SUCCESS",
  710. title: name
  711. };
  712. var $file = $("#" + id);
  713. _this.imageList[$file.index()] = pic; //按选择文件排序;_this.imageList.push(pic);
  714. $file.append('<span class="success"></span>');
  715. uploader.skipFile(file);
  716. var $li = $("#" + file.id),
  717. $percent = $li.find(".progress span");
  718. $percent.css("width", 1 * 100 + "%");
  719. percentages[file.id][1] = 1;
  720. updateTotalProgress();
  721. setState("confirm")
  722. });
  723. })(i);
  724. }
  725. });
  726. $upload.addClass('state-' + state);
  727. updateTotalProgress();
  728. },
  729. getQueueCount: function () {
  730. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  731. for (i = 0; file = files[i++];) {
  732. status = file.getStatus();
  733. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  734. }
  735. return readyFile;
  736. },
  737. destroy: function () {
  738. this.$wrap.remove();
  739. },
  740. getInsertList: function () {
  741. var i, data, list = [],
  742. align = getAlign(),
  743. prefix = editor.getOpt('imageUrlPrefix');
  744. for (i = 0; i < this.imageList.length; i++) {
  745. data = this.imageList[i];
  746. if (data == undefined) { //避免图片上传失败
  747. continue;
  748. }
  749. list.push({
  750. src: prefix + data.url,
  751. _src: prefix + data.url,
  752. alt: data.original,
  753. floatStyle: align
  754. });
  755. }
  756. return list;
  757. }
  758. };
  759. /* 在线图片 */
  760. function OnlineImage(target) {
  761. this.container = utils.isString(target) ? document.getElementById(target) : target;
  762. this.init();
  763. }
  764. OnlineImage.prototype = {
  765. init: function () {
  766. this.reset();
  767. this.initEvents();
  768. },
  769. /* 初始化容器 */
  770. initContainer: function () {
  771. this.container.innerHTML = '';
  772. this.list = document.createElement('ul');
  773. this.clearFloat = document.createElement('li');
  774. domUtils.addClass(this.list, 'list');
  775. domUtils.addClass(this.clearFloat, 'clearFloat');
  776. this.list.appendChild(this.clearFloat);
  777. this.container.appendChild(this.list);
  778. },
  779. /* 初始化滚动事件,滚动到地步自动拉取数据 */
  780. initEvents: function () {
  781. var _this = this;
  782. /* 滚动拉取图片 */
  783. domUtils.on($G('imageList'), 'scroll', function (e) {
  784. var panel = this;
  785. if (panel.scrollHeight - (panel.offsetHeight + panel.scrollTop) < 10) {
  786. _this.getImageData();
  787. }
  788. });
  789. /* 选中图片 */
  790. domUtils.on(this.container, 'click', function (e) {
  791. var target = e.target || e.srcElement,
  792. li = target.parentNode;
  793. if (li.tagName.toLowerCase() == 'li') {
  794. if (domUtils.hasClass(li, 'selected')) {
  795. domUtils.removeClasses(li, 'selected');
  796. } else {
  797. domUtils.addClass(li, 'selected');
  798. }
  799. }
  800. });
  801. },
  802. /* 初始化第一次的数据 */
  803. initData: function () {
  804. /* 拉取数据需要使用的值 */
  805. this.state = 0;
  806. this.listSize = editor.getOpt('imageManagerListSize');
  807. this.listIndex = 0;
  808. this.listEnd = false;
  809. /* 第一次拉取数据 */
  810. this.getImageData();
  811. },
  812. /* 重置界面 */
  813. reset: function () {
  814. this.initContainer();
  815. this.initData();
  816. },
  817. /* 向后台拉取图片列表数据 */
  818. getImageData: function () {
  819. var _this = this;
  820. if (!_this.listEnd && !this.isLoadingData) {
  821. this.isLoadingData = true;
  822. var url = editor.getActionUrl(editor.getOpt('imageManagerActionName')),
  823. isJsonp = utils.isCrossDomainUrl(url);
  824. ajax.request(url, {
  825. 'timeout': 100000,
  826. 'dataType': isJsonp ? 'jsonp' : '',
  827. 'data': utils.extend({
  828. start: this.listIndex,
  829. size: this.listSize
  830. }, editor.queryCommandValue('serverparam')),
  831. 'method': 'get',
  832. 'onsuccess': function (r) {
  833. try {
  834. var json = isJsonp ? r : eval('(' + r.responseText + ')');
  835. if (json.state == 'SUCCESS') {
  836. _this.pushData(json.list);
  837. _this.listIndex = parseInt(json.start) + parseInt(json.list.length);
  838. if (_this.listIndex >= json.total) {
  839. _this.listEnd = true;
  840. }
  841. _this.isLoadingData = false;
  842. }
  843. } catch (e) {
  844. if (r.responseText.indexOf('ue_separate_ue') != -1) {
  845. var list = r.responseText.split(r.responseText);
  846. _this.pushData(list);
  847. _this.listIndex = parseInt(list.length);
  848. _this.listEnd = true;
  849. _this.isLoadingData = false;
  850. }
  851. }
  852. },
  853. 'onerror': function () {
  854. _this.isLoadingData = false;
  855. }
  856. });
  857. }
  858. },
  859. /* 添加图片到列表界面上 */
  860. pushData: function (list) {
  861. var i, item, img, icon, _this = this,
  862. urlPrefix = editor.getOpt('imageManagerUrlPrefix');
  863. for (i = 0; i < list.length; i++) {
  864. if (list[i] && list[i].url) {
  865. item = document.createElement('li');
  866. img = document.createElement('img');
  867. icon = document.createElement('span');
  868. domUtils.on(img, 'load', (function (image) {
  869. return function () {
  870. _this.scale(image, image.parentNode.offsetWidth, image.parentNode.offsetHeight);
  871. }
  872. })(img));
  873. img.width = 113;
  874. img.setAttribute('src', urlPrefix + list[i].url + (list[i].url.indexOf('?') == -1 ? '?noCache=' : '&noCache=') + (+new Date()).toString(36));
  875. img.setAttribute('_src', urlPrefix + list[i].url);
  876. domUtils.addClass(icon, 'icon');
  877. item.appendChild(img);
  878. item.appendChild(icon);
  879. this.list.insertBefore(item, this.clearFloat);
  880. }
  881. }
  882. },
  883. /* 改变图片大小 */
  884. scale: function (img, w, h, type) {
  885. var ow = img.width,
  886. oh = img.height;
  887. if (type == 'justify') {
  888. if (ow >= oh) {
  889. img.width = w;
  890. img.height = h * oh / ow;
  891. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  892. } else {
  893. img.width = w * ow / oh;
  894. img.height = h;
  895. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  896. }
  897. } else {
  898. if (ow >= oh) {
  899. img.width = w * ow / oh;
  900. img.height = h;
  901. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  902. } else {
  903. img.width = w;
  904. img.height = h * oh / ow;
  905. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  906. }
  907. }
  908. },
  909. getInsertList: function () {
  910. var i, lis = this.list.children, list = [], align = getAlign();
  911. for (i = 0; i < lis.length; i++) {
  912. if (domUtils.hasClass(lis[i], 'selected')) {
  913. var img = lis[i].firstChild,
  914. src = img.getAttribute('_src');
  915. list.push({
  916. src: src,
  917. _src: src,
  918. alt: src.substr(src.lastIndexOf('/') + 1),
  919. floatStyle: align
  920. });
  921. }
  922. }
  923. return list;
  924. }
  925. };
  926. /*搜索图片 */
  927. function SearchImage() {
  928. this.init();
  929. }
  930. SearchImage.prototype = {
  931. init: function () {
  932. this.initEvents();
  933. },
  934. initEvents: function () {
  935. var _this = this;
  936. /* 点击搜索按钮 */
  937. domUtils.on($G('searchBtn'), 'click', function () {
  938. var key = $G('searchTxt').value;
  939. if (key && key != lang.searchRemind) {
  940. _this.getImageData();
  941. }
  942. });
  943. /* 点击清除妞 */
  944. domUtils.on($G('searchReset'), 'click', function () {
  945. $G('searchTxt').value = lang.searchRemind;
  946. $G('searchListUl').innerHTML = '';
  947. $G('searchType').selectedIndex = 0;
  948. });
  949. /* 搜索框聚焦 */
  950. domUtils.on($G('searchTxt'), 'focus', function () {
  951. var key = $G('searchTxt').value;
  952. if (key && key == lang.searchRemind) {
  953. $G('searchTxt').value = '';
  954. }
  955. });
  956. /* 搜索框回车键搜索 */
  957. domUtils.on($G('searchTxt'), 'keydown', function (e) {
  958. var keyCode = e.keyCode || e.which;
  959. if (keyCode == 13) {
  960. $G('searchBtn').click();
  961. }
  962. });
  963. /* 选中图片 */
  964. domUtils.on($G('searchList'), 'click', function (e) {
  965. var target = e.target || e.srcElement,
  966. li = target.parentNode.parentNode;
  967. if (li.tagName.toLowerCase() == 'li') {
  968. if (domUtils.hasClass(li, 'selected')) {
  969. domUtils.removeClasses(li, 'selected');
  970. } else {
  971. domUtils.addClass(li, 'selected');
  972. }
  973. }
  974. });
  975. },
  976. /* 改变图片大小 */
  977. scale: function (img, w, h) {
  978. var ow = img.width,
  979. oh = img.height;
  980. if (ow >= oh) {
  981. img.width = w * ow / oh;
  982. img.height = h;
  983. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  984. } else {
  985. img.width = w;
  986. img.height = h * oh / ow;
  987. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  988. }
  989. },
  990. getImageData: function () {
  991. var _this = this,
  992. key = $G('searchTxt').value,
  993. type = $G('searchType').value,
  994. keepOriginName = editor.options.keepOriginName ? "1" : "0",
  995. url = "http://image.baidu.com/i?ct=201326592&cl=2&lm=-1&st=-1&tn=baiduimagejson&istype=2&rn=32&fm=index&pv=&word=" + key + type + "&ie=utf-8&oe=utf-8&keeporiginname=" + keepOriginName + "&" + +new Date;
  996. $G('searchListUl').innerHTML = lang.searchLoading;
  997. ajax.request(url, {
  998. 'dataType': 'jsonp',
  999. 'charset': 'GB18030',
  1000. 'onsuccess': function (json) {
  1001. var list = [];
  1002. if (json && json.data) {
  1003. for (var i = 0; i < json.data.length; i++) {
  1004. if (json.data[i].objURL) {
  1005. list.push({
  1006. title: json.data[i].fromPageTitleEnc,
  1007. src: json.data[i].objURL,
  1008. url: json.data[i].fromURL
  1009. });
  1010. }
  1011. }
  1012. }
  1013. _this.setList(list);
  1014. },
  1015. 'onerror': function () {
  1016. $G('searchListUl').innerHTML = lang.searchRetry;
  1017. }
  1018. });
  1019. },
  1020. /* 添加图片到列表界面上 */
  1021. setList: function (list) {
  1022. var i, item, p, img, link, _this = this,
  1023. listUl = $G('searchListUl');
  1024. listUl.innerHTML = '';
  1025. if (list.length) {
  1026. for (i = 0; i < list.length; i++) {
  1027. item = document.createElement('li');
  1028. p = document.createElement('p');
  1029. img = document.createElement('img');
  1030. link = document.createElement('a');
  1031. img.onload = function () {
  1032. _this.scale(this, 113, 113);
  1033. };
  1034. img.width = 113;
  1035. img.setAttribute('src', list[i].src);
  1036. link.href = list[i].url;
  1037. link.target = '_blank';
  1038. link.title = list[i].title;
  1039. link.innerHTML = list[i].title;
  1040. p.appendChild(img);
  1041. item.appendChild(p);
  1042. item.appendChild(link);
  1043. listUl.appendChild(item);
  1044. }
  1045. } else {
  1046. listUl.innerHTML = lang.searchRetry;
  1047. }
  1048. },
  1049. getInsertList: function () {
  1050. var child,
  1051. src,
  1052. align = getAlign(),
  1053. list = [],
  1054. items = $G('searchListUl').children;
  1055. for (var i = 0; i < items.length; i++) {
  1056. child = items[i].firstChild && items[i].firstChild.firstChild;
  1057. if (child.tagName && child.tagName.toLowerCase() == 'img' && domUtils.hasClass(items[i], 'selected')) {
  1058. src = child.src;
  1059. list.push({
  1060. src: src,
  1061. _src: src,
  1062. alt: src.substr(src.lastIndexOf('/') + 1),
  1063. floatStyle: align
  1064. });
  1065. }
  1066. }
  1067. return list;
  1068. }
  1069. };
  1070. })();