image.js 41 KB

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