image.js 39 KB

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