image.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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(); $info.hide();
  568. uploader.refresh();
  569. break;
  570. /* 可以开始上传 */
  571. case 'ready':
  572. $placeHolder.addClass('element-invisible');
  573. $queue.removeClass('element-invisible');
  574. $statusBar.removeClass('element-invisible');
  575. $progress.hide(); $info.show();
  576. $upload.text(lang.uploadStart);
  577. uploader.refresh();
  578. break;
  579. /* 上传中 */
  580. case 'uploading':
  581. $progress.show(); $info.hide();
  582. $upload.text(lang.uploadPause);
  583. break;
  584. /* 暂停上传 */
  585. case 'paused':
  586. $progress.show(); $info.hide();
  587. $upload.text(lang.uploadContinue);
  588. break;
  589. case 'confirm':
  590. $progress.show(); $info.hide();
  591. $upload.text(lang.uploadStart);
  592. stats = uploader.getStats();
  593. if (stats.successNum && !stats.uploadFailNum) {
  594. setState('finish');
  595. return;
  596. }
  597. break;
  598. case 'finish':
  599. $progress.hide(); $info.show();
  600. if (stats.uploadFailNum) {
  601. $upload.text(lang.uploadRetry);
  602. } else {
  603. $upload.text(lang.uploadStart);
  604. }
  605. break;
  606. }
  607. state = val;
  608. updateStatus();
  609. }
  610. if (!_this.getQueueCount()) {
  611. $upload.addClass('disabled')
  612. } else {
  613. $upload.removeClass('disabled')
  614. }
  615. }
  616. function updateStatus() {
  617. var text = '', stats;
  618. if (state === 'ready') {
  619. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  620. } else if (state === 'confirm') {
  621. stats = uploader.getStats();
  622. if (stats.uploadFailNum) {
  623. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  624. }
  625. } else {
  626. stats = uploader.getStats();
  627. text = lang.updateStatusFinish.replace('_', fileCount).
  628. replace('_KB', WebUploader.formatSize(fileSize)).
  629. replace('_', stats.successNum);
  630. if (stats.uploadFailNum) {
  631. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  632. }
  633. }
  634. $info.html(text);
  635. }
  636. uploader.on('fileQueued', function (file) {
  637. fileCount++;
  638. fileSize += file.size;
  639. if (fileCount === 1) {
  640. $placeHolder.addClass('element-invisible');
  641. $statusBar.show();
  642. }
  643. addFile(file);
  644. });
  645. uploader.on('fileDequeued', function (file) {
  646. if (file.ext && acceptExtensions.indexOf(file.ext.toLowerCase()) != -1 && file.size <= imageMaxSize) {
  647. fileCount--;
  648. fileSize -= file.size;
  649. }
  650. removeFile(file);
  651. updateTotalProgress();
  652. });
  653. uploader.on('filesQueued', function (file) {
  654. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  655. setState('ready');
  656. }
  657. updateTotalProgress();
  658. });
  659. uploader.on('all', function (type, files) {
  660. switch (type) {
  661. case 'uploadFinished':
  662. setState('confirm', files);
  663. break;
  664. case 'startUpload':
  665. /* 添加额外的GET参数 */
  666. var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '',
  667. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + 'encode=utf-8&' + params);
  668. uploader.option('server', url);
  669. setState('uploading', files);
  670. break;
  671. case 'stopUpload':
  672. setState('paused', files);
  673. break;
  674. }
  675. });
  676. uploader.on('uploadBeforeSend', function (file, data, header) {
  677. //这里可以通过data对象添加POST参数
  678. if (actionUrl.toLowerCase().indexOf('jsp') != -1) {
  679. header['X-Requested-With'] = 'XMLHttpRequest';
  680. }
  681. });
  682. uploader.on('uploadProgress', function (file, percentage) {
  683. var $li = $('#' + file.id),
  684. $percent = $li.find('.progress span');
  685. $percent.css('width', percentage * 100 + '%');
  686. percentages[ file.id ][ 1 ] = percentage;
  687. updateTotalProgress();
  688. });
  689. uploader.on('uploadSuccess', function (file, ret) {
  690. var $file = $('#' + file.id);
  691. try {
  692. var responseText = (ret._raw || ret),
  693. json = utils.str2json(responseText);
  694. if (json.state == 'SUCCESS') {
  695. _this.imageList.push(json);
  696. $file.append('<span class="success"></span>');
  697. // 触发上传图片事件
  698. editor.fireEvent("uploadsuccess", {
  699. res: json,
  700. type: 'image'
  701. });
  702. } else {
  703. $file.find('.error').text(json.state).show();
  704. }
  705. } catch (e) {
  706. $file.find('.error').text(lang.errorServerUpload).show();
  707. }
  708. });
  709. uploader.on('uploadError', function (file, code) {
  710. });
  711. uploader.on('error', function (code, file) {
  712. if (code == 'Q_TYPE_DENIED' || code == 'F_EXCEED_SIZE') {
  713. addFile(file);
  714. }
  715. });
  716. uploader.on('uploadComplete', function (file, ret) {
  717. });
  718. $upload.on('click', function () {
  719. if ($(this).hasClass('disabled')) {
  720. return false;
  721. }
  722. if (state === 'ready') {
  723. uploader.upload();
  724. } else if (state === 'paused') {
  725. uploader.upload();
  726. } else if (state === 'uploading') {
  727. uploader.stop();
  728. }
  729. });
  730. $upload.addClass('state-' + state);
  731. updateTotalProgress();
  732. },
  733. getQueueCount: function () {
  734. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  735. for (i = 0; file = files[i++]; ) {
  736. status = file.getStatus();
  737. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  738. }
  739. return readyFile;
  740. },
  741. destroy: function () {
  742. this.$wrap.remove();
  743. },
  744. getInsertList: function () {
  745. var i, data, list = [],
  746. align = getAlign(),
  747. prefix = editor.getOpt('imageUrlPrefix');
  748. for (i = 0; i < this.imageList.length; i++) {
  749. data = this.imageList[i];
  750. list.push({
  751. src: prefix + data.url,
  752. _src: prefix + data.url,
  753. alt: data.original,
  754. floatStyle: align
  755. });
  756. }
  757. return list;
  758. }
  759. };
  760. /* 在线图片 */
  761. function OnlineImage(target) {
  762. this.container = utils.isString(target) ? document.getElementById(target) : target;
  763. this.init();
  764. }
  765. OnlineImage.prototype = {
  766. init: function () {
  767. this.reset();
  768. this.initEvents();
  769. },
  770. /* 初始化容器 */
  771. initContainer: function () {
  772. this.container.innerHTML = '';
  773. this.list = document.createElement('ul');
  774. this.clearFloat = document.createElement('li');
  775. domUtils.addClass(this.list, 'list');
  776. domUtils.addClass(this.clearFloat, 'clearFloat');
  777. this.list.appendChild(this.clearFloat);
  778. this.container.appendChild(this.list);
  779. },
  780. /* 初始化滚动事件,滚动到地步自动拉取数据 */
  781. initEvents: function () {
  782. var _this = this;
  783. /* 滚动拉取图片 */
  784. domUtils.on($G('imageList'), 'scroll', function(e){
  785. var panel = this;
  786. if (panel.scrollHeight - (panel.offsetHeight + panel.scrollTop) < 10) {
  787. _this.getImageData();
  788. }
  789. });
  790. /* 选中图片 */
  791. domUtils.on(this.container, 'click', function (e) {
  792. var target = e.target || e.srcElement,
  793. li = target.parentNode;
  794. if (li.tagName.toLowerCase() == 'li') {
  795. if (domUtils.hasClass(li, 'selected')) {
  796. domUtils.removeClasses(li, 'selected');
  797. } else {
  798. domUtils.addClass(li, 'selected');
  799. }
  800. }
  801. });
  802. },
  803. /* 初始化第一次的数据 */
  804. initData: function () {
  805. /* 拉取数据需要使用的值 */
  806. this.state = 0;
  807. this.listSize = editor.getOpt('imageManagerListSize');
  808. this.listIndex = 0;
  809. this.listEnd = false;
  810. /* 第一次拉取数据 */
  811. this.getImageData();
  812. },
  813. /* 重置界面 */
  814. reset: function() {
  815. this.initContainer();
  816. this.initData();
  817. },
  818. /* 向后台拉取图片列表数据 */
  819. getImageData: function () {
  820. var _this = this;
  821. if(!_this.listEnd && !this.isLoadingData) {
  822. this.isLoadingData = true;
  823. var url = editor.getActionUrl(editor.getOpt('imageManagerActionName')),
  824. isJsonp = utils.isCrossDomainUrl(url);
  825. ajax.request(url, {
  826. 'timeout': 100000,
  827. 'dataType': isJsonp ? 'jsonp':'',
  828. 'headers': editor.options.serverHeaders || {},
  829. 'data': utils.extend({
  830. start: this.listIndex,
  831. size: this.listSize
  832. }, editor.queryCommandValue('serverparam')),
  833. 'method': 'get',
  834. 'onsuccess': function (r) {
  835. try {
  836. var json = isJsonp ? r:eval('(' + r.responseText + ')');
  837. if (json.state === 'SUCCESS') {
  838. _this.pushData(json.list);
  839. _this.listIndex = parseInt(json.start) + parseInt(json.list.length);
  840. if(_this.listIndex >= json.total) {
  841. _this.listEnd = true;
  842. }
  843. _this.isLoadingData = false;
  844. }
  845. } catch (e) {
  846. if(r.responseText.indexOf('ue_separate_ue') != -1) {
  847. var list = r.responseText.split(r.responseText);
  848. _this.pushData(list);
  849. _this.listIndex = parseInt(list.length);
  850. _this.listEnd = true;
  851. _this.isLoadingData = false;
  852. }
  853. }
  854. },
  855. 'onerror': function () {
  856. _this.isLoadingData = false;
  857. }
  858. });
  859. }
  860. },
  861. /* 添加图片到列表界面上 */
  862. pushData: function (list) {
  863. var i, item, img, icon, _this = this,
  864. urlPrefix = editor.getOpt('imageManagerUrlPrefix');
  865. for (i = 0; i < list.length; i++) {
  866. if(list[i] && list[i].url) {
  867. item = document.createElement('li');
  868. img = document.createElement('img');
  869. icon = document.createElement('span');
  870. domUtils.on(img, 'load', (function(image){
  871. return function(){
  872. _this.scale(image, image.parentNode.offsetWidth, image.parentNode.offsetHeight);
  873. }
  874. })(img));
  875. img.width = 113;
  876. img.setAttribute('src', urlPrefix + list[i].url + (list[i].url.indexOf('?') == -1 ? '?noCache=':'&noCache=') + (+new Date()).toString(36) );
  877. img.setAttribute('_src', urlPrefix + list[i].url);
  878. domUtils.addClass(icon, 'icon');
  879. item.appendChild(img);
  880. item.appendChild(icon);
  881. this.list.insertBefore(item, this.clearFloat);
  882. }
  883. }
  884. },
  885. /* 改变图片大小 */
  886. scale: function (img, w, h, type) {
  887. var ow = img.width,
  888. oh = img.height;
  889. if (type == 'justify') {
  890. if (ow >= oh) {
  891. img.width = w;
  892. img.height = h * oh / ow;
  893. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  894. } else {
  895. img.width = w * ow / oh;
  896. img.height = h;
  897. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  898. }
  899. } else {
  900. if (ow >= oh) {
  901. img.width = w * ow / oh;
  902. img.height = h;
  903. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  904. } else {
  905. img.width = w;
  906. img.height = h * oh / ow;
  907. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  908. }
  909. }
  910. },
  911. getInsertList: function () {
  912. var i, lis = this.list.children, list = [], align = getAlign();
  913. for (i = 0; i < lis.length; i++) {
  914. if (domUtils.hasClass(lis[i], 'selected')) {
  915. var img = lis[i].firstChild,
  916. src = img.getAttribute('_src');
  917. list.push({
  918. src: src,
  919. _src: src,
  920. alt: src.substr(src.lastIndexOf('/') + 1),
  921. floatStyle: align
  922. });
  923. }
  924. }
  925. return list;
  926. }
  927. };
  928. })();