attachment.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. /**
  2. * User: Jinqn
  3. * Date: 14-04-08
  4. * Time: 下午16:34
  5. * 上传图片对话框逻辑代码,包括tab: 远程图片/上传图片/在线图片/搜索图片
  6. */
  7. (function () {
  8. var uploadFile,
  9. onlineFile;
  10. window.onload = function () {
  11. initTabs();
  12. initButtons();
  13. };
  14. /* 初始化tab标签 */
  15. function initTabs() {
  16. var tabs = $G('tabhead').children;
  17. for (var i = 0; i < tabs.length; i++) {
  18. domUtils.on(tabs[i], "click", function (e) {
  19. var target = e.target || e.srcElement;
  20. setTabFocus(target.getAttribute('data-content-id'));
  21. });
  22. }
  23. setTabFocus('upload');
  24. }
  25. /* 初始化tabbody */
  26. function setTabFocus(id) {
  27. if (!id) return;
  28. var i, bodyId, tabs = $G('tabhead').children;
  29. for (i = 0; i < tabs.length; i++) {
  30. bodyId = tabs[i].getAttribute('data-content-id')
  31. if (bodyId == id) {
  32. domUtils.addClass(tabs[i], 'focus');
  33. domUtils.addClass($G(bodyId), 'focus');
  34. } else {
  35. domUtils.removeClasses(tabs[i], 'focus');
  36. domUtils.removeClasses($G(bodyId), 'focus');
  37. }
  38. }
  39. switch (id) {
  40. case 'upload':
  41. uploadFile = uploadFile || new UploadFile('queueList');
  42. break;
  43. case 'online':
  44. editor.fireEvent("file.online", editor, dialog)
  45. //onlineFile = onlineFile || new OnlineFile('fileList');
  46. break;
  47. }
  48. }
  49. /* 初始化onok事件 */
  50. function initButtons() {
  51. dialog.onok = function () {
  52. var list = [], id, tabs = $G('tabhead').children;
  53. for (var i = 0; i < tabs.length; i++) {
  54. if (domUtils.hasClass(tabs[i], 'focus')) {
  55. id = tabs[i].getAttribute('data-content-id');
  56. break;
  57. }
  58. }
  59. switch (id) {
  60. case 'upload':
  61. list = uploadFile.getInsertList();
  62. var count = uploadFile.getQueueCount();
  63. if (count) {
  64. $('.info', '#queueList').html('<span style="color:red;">' + '还有2个未上传文件'.replace(/[\d]/, count) + '</span>');
  65. return false;
  66. }
  67. break;
  68. case 'online':
  69. list = onlineFile.getInsertList();
  70. break;
  71. }
  72. editor.execCommand('insertfile', list);
  73. };
  74. }
  75. /* 上传附件 */
  76. function UploadFile(target) {
  77. this.$wrap = target.constructor == String ? $('#' + target) : $(target);
  78. this.init();
  79. }
  80. UploadFile.prototype = {
  81. init: function () {
  82. this.fileList = [];
  83. this.initContainer();
  84. this.initUploader();
  85. },
  86. initContainer: function () {
  87. this.$queue = this.$wrap.find('.filelist');
  88. },
  89. /* 初始化容器 */
  90. initUploader: function () {
  91. var _this = this,
  92. $ = jQuery, // just in case. Make sure it's not an other libaray.
  93. $wrap = _this.$wrap,
  94. // 图片容器
  95. $queue = $wrap.find('.filelist'),
  96. // 状态栏,包括进度和控制按钮
  97. $statusBar = $wrap.find('.statusBar'),
  98. // 文件总体选择信息。
  99. $info = $statusBar.find('.info'),
  100. // 上传按钮
  101. $upload = $wrap.find('.uploadBtn'),
  102. // 上传按钮
  103. $filePickerBtn = $wrap.find('.filePickerBtn'),
  104. // 上传按钮
  105. $filePickerBlock = $wrap.find('.filePickerBlock'),
  106. // 没选择文件之前的内容。
  107. $placeHolder = $wrap.find('.placeholder'),
  108. // 总体进度条
  109. $progress = $statusBar.find('.progress').hide(),
  110. // 添加的文件数量
  111. fileCount = 0,
  112. // 添加的文件总大小
  113. fileSize = 0,
  114. // 优化retina, 在retina下这个值是2
  115. ratio = window.devicePixelRatio || 1,
  116. // 缩略图大小
  117. thumbnailWidth = 113 * ratio,
  118. thumbnailHeight = 113 * ratio,
  119. // 可能有pedding, ready, uploading, confirm, done.
  120. state = '',
  121. // 所有文件的进度信息,key为file id
  122. percentages = {},
  123. supportTransition = (function () {
  124. var s = document.createElement('p').style,
  125. r = 'transition' in s ||
  126. 'WebkitTransition' in s ||
  127. 'MozTransition' in s ||
  128. 'msTransition' in s ||
  129. 'OTransition' in s;
  130. s = null;
  131. return r;
  132. })(),
  133. // WebUploader实例
  134. uploader,
  135. actionUrl = editor.getActionUrl(editor.getOpt('fileActionName')),
  136. fileMaxSize = editor.getOpt('fileMaxSize'),
  137. acceptExtensions = (editor.getOpt('fileAllowFiles') || []).join('').replace(/\./g, ',').replace(/^[,]/, '');
  138. ;
  139. if (!WebUploader.Uploader.support()) {
  140. $('#filePickerReady').after($('<div>').html(lang.errorNotSupport)).hide();
  141. return;
  142. } else if (!editor.getOpt('fileActionName')) {
  143. $('#filePickerReady').after($('<div>').html(lang.errorLoadConfig)).hide();
  144. return;
  145. }
  146. var uploaderOption = {
  147. pick: {
  148. id: '#filePickerReady',
  149. label: lang.uploadSelectFile
  150. },
  151. swf: '../../third-party/webuploader/Uploader.swf',
  152. server: actionUrl,
  153. fileVal: editor.getOpt('fileFieldName'),
  154. duplicate: true,
  155. fileSingleSizeLimit: fileMaxSize,
  156. headers: editor.getOpt('serverHeaders') || {},
  157. compress: false
  158. };
  159. if(editor.getOpt('uploadServiceEnable')) {
  160. uploaderOption.customUpload = function (file, callback) {
  161. editor.getOpt('uploadServiceUpload')('attachment', file, {
  162. success: function( res ) {
  163. callback.onSuccess(file, {_raw:JSON.stringify(res)});
  164. },
  165. error: function( err ) {
  166. callback.onError(file, err);
  167. },
  168. progress: function( percent ) {
  169. callback.onProgress(file, percent);
  170. }
  171. }, {
  172. from: 'attachment'
  173. });
  174. };
  175. }
  176. uploader = _this.uploader = WebUploader.create(uploaderOption);
  177. uploader.addButton({
  178. id: '#filePickerBlock'
  179. });
  180. uploader.addButton({
  181. id: '#filePickerBtn',
  182. label: lang.uploadAddFile
  183. });
  184. setState('pedding');
  185. // 当有文件添加进来时执行,负责view的创建
  186. function addFile(file) {
  187. var $li = $('<li id="' + file.id + '">' +
  188. '<p class="title">' + file.name + '</p>' +
  189. '<p class="imgWrap"></p>' +
  190. '<p class="progress"><span></span></p>' +
  191. '</li>'),
  192. $btns = $('<div class="file-panel">' +
  193. '<span class="cancel">' + lang.uploadDelete + '</span>' +
  194. '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
  195. '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
  196. $prgress = $li.find('p.progress span'),
  197. $wrap = $li.find('p.imgWrap'),
  198. $info = $('<p class="error"></p>').hide().appendTo($li),
  199. showError = function (code) {
  200. switch (code) {
  201. case 'exceed_size':
  202. text = lang.errorExceedSize;
  203. break;
  204. case 'interrupt':
  205. text = lang.errorInterrupt;
  206. break;
  207. case 'http':
  208. text = lang.errorHttp;
  209. break;
  210. case 'not_allow_type':
  211. text = lang.errorFileType;
  212. break;
  213. default:
  214. text = lang.errorUploadRetry;
  215. break;
  216. }
  217. $info.text(text).show();
  218. };
  219. if (file.getStatus() === 'invalid') {
  220. showError(file.statusText);
  221. } else {
  222. $wrap.text(lang.uploadPreview);
  223. if ('|png|jpg|jpeg|bmp|gif|'.indexOf('|' + file.ext.toLowerCase() + '|') == -1) {
  224. $wrap.empty().addClass('notimage').append('<i class="file-preview file-type-' + file.ext.toLowerCase() + '"></i>' +
  225. '<span class="file-title" title="' + file.name + '">' + file.name + '</span>');
  226. } else {
  227. if (browser.ie && browser.version <= 7) {
  228. $wrap.text(lang.uploadNoPreview);
  229. } else {
  230. uploader.makeThumb(file, function (error, src) {
  231. if (error || !src) {
  232. $wrap.text(lang.uploadNoPreview);
  233. } else {
  234. var $img = $('<img src="' + src + '">');
  235. $wrap.empty().append($img);
  236. $img.on('error', function () {
  237. $wrap.text(lang.uploadNoPreview);
  238. });
  239. }
  240. }, thumbnailWidth, thumbnailHeight);
  241. }
  242. }
  243. percentages[file.id] = [file.size, 0];
  244. file.rotation = 0;
  245. /* 检查文件格式 */
  246. if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
  247. showError('not_allow_type');
  248. uploader.removeFile(file);
  249. }
  250. }
  251. file.on('statuschange', function (cur, prev) {
  252. if (prev === 'progress') {
  253. $prgress.hide().width(0);
  254. } else if (prev === 'queued') {
  255. $li.off('mouseenter mouseleave');
  256. $btns.remove();
  257. }
  258. // 成功
  259. if (cur === 'error' || cur === 'invalid') {
  260. showError(file.statusText);
  261. percentages[file.id][1] = 1;
  262. } else if (cur === 'interrupt') {
  263. showError('interrupt');
  264. } else if (cur === 'queued') {
  265. percentages[file.id][1] = 0;
  266. } else if (cur === 'progress') {
  267. $info.hide();
  268. $prgress.css('display', 'block');
  269. } else if (cur === 'complete') {
  270. }
  271. $li.removeClass('state-' + prev).addClass('state-' + cur);
  272. });
  273. $li.on('mouseenter', function () {
  274. $btns.stop().animate({height: 30});
  275. });
  276. $li.on('mouseleave', function () {
  277. $btns.stop().animate({height: 0});
  278. });
  279. $btns.on('click', 'span', function () {
  280. var index = $(this).index(),
  281. deg;
  282. switch (index) {
  283. case 0:
  284. uploader.removeFile(file);
  285. return;
  286. case 1:
  287. file.rotation += 90;
  288. break;
  289. case 2:
  290. file.rotation -= 90;
  291. break;
  292. }
  293. if (supportTransition) {
  294. deg = 'rotate(' + file.rotation + 'deg)';
  295. $wrap.css({
  296. '-webkit-transform': deg,
  297. '-mos-transform': deg,
  298. '-o-transform': deg,
  299. 'transform': deg
  300. });
  301. } else {
  302. $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
  303. }
  304. });
  305. $li.insertBefore($filePickerBlock);
  306. }
  307. // 负责view的销毁
  308. function removeFile(file) {
  309. var $li = $('#' + file.id);
  310. delete percentages[file.id];
  311. updateTotalProgress();
  312. $li.off().find('.file-panel').off().end().remove();
  313. }
  314. function updateTotalProgress() {
  315. var loaded = 0,
  316. total = 0,
  317. spans = $progress.children(),
  318. percent;
  319. $.each(percentages, function (k, v) {
  320. total += v[0];
  321. loaded += v[0] * v[1];
  322. });
  323. percent = total ? loaded / total : 0;
  324. spans.eq(0).text(Math.round(percent * 100) + '%');
  325. spans.eq(1).css('width', Math.round(percent * 100) + '%');
  326. updateStatus();
  327. }
  328. function setState(val, files) {
  329. if (val != state) {
  330. var stats = uploader.getStats();
  331. $upload.removeClass('state-' + state);
  332. $upload.addClass('state-' + val);
  333. switch (val) {
  334. /* 未选择文件 */
  335. case 'pedding':
  336. $queue.addClass('element-invisible');
  337. $statusBar.addClass('element-invisible');
  338. $placeHolder.removeClass('element-invisible');
  339. $progress.hide();
  340. $info.hide();
  341. uploader.refresh();
  342. break;
  343. /* 可以开始上传 */
  344. case 'ready':
  345. $placeHolder.addClass('element-invisible');
  346. $queue.removeClass('element-invisible');
  347. $statusBar.removeClass('element-invisible');
  348. $progress.hide();
  349. $info.show();
  350. $upload.text(lang.uploadStart);
  351. uploader.refresh();
  352. break;
  353. /* 上传中 */
  354. case 'uploading':
  355. $progress.show();
  356. $info.hide();
  357. $upload.text(lang.uploadPause);
  358. break;
  359. /* 暂停上传 */
  360. case 'paused':
  361. $progress.show();
  362. $info.hide();
  363. $upload.text(lang.uploadContinue);
  364. break;
  365. case 'confirm':
  366. $progress.show();
  367. $info.hide();
  368. $upload.text(lang.uploadStart);
  369. stats = uploader.getStats();
  370. if (stats.successNum && !stats.uploadFailNum) {
  371. setState('finish');
  372. return;
  373. }
  374. break;
  375. case 'finish':
  376. $progress.hide();
  377. $info.show();
  378. if (stats.uploadFailNum) {
  379. $upload.text(lang.uploadRetry);
  380. } else {
  381. $upload.text(lang.uploadStart);
  382. }
  383. break;
  384. }
  385. state = val;
  386. updateStatus();
  387. }
  388. if (!_this.getQueueCount()) {
  389. $upload.addClass('disabled')
  390. } else {
  391. $upload.removeClass('disabled')
  392. }
  393. }
  394. function updateStatus() {
  395. var text = '', stats;
  396. if (state === 'ready') {
  397. text = lang.updateStatusReady.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize));
  398. } else if (state === 'confirm') {
  399. stats = uploader.getStats();
  400. if (stats.uploadFailNum) {
  401. text = lang.updateStatusConfirm.replace('_', stats.successNum).replace('_', stats.successNum);
  402. }
  403. } else {
  404. stats = uploader.getStats();
  405. text = lang.updateStatusFinish.replace('_', fileCount).replace('_KB', WebUploader.formatSize(fileSize)).replace('_', stats.successNum);
  406. if (stats.uploadFailNum) {
  407. text += lang.updateStatusError.replace('_', stats.uploadFailNum);
  408. }
  409. }
  410. $info.html(text);
  411. }
  412. uploader.on('fileQueued', function (file) {
  413. if (file.ext && acceptExtensions.indexOf(file.ext.toLowerCase()) != -1 && file.size <= fileMaxSize) {
  414. fileCount++;
  415. fileSize += file.size;
  416. }
  417. if (fileCount === 1) {
  418. $placeHolder.addClass('element-invisible');
  419. $statusBar.show();
  420. }
  421. addFile(file);
  422. });
  423. uploader.on('fileDequeued', function (file) {
  424. if (file.ext && acceptExtensions.indexOf(file.ext.toLowerCase()) != -1 && file.size <= fileMaxSize) {
  425. fileCount--;
  426. fileSize -= file.size;
  427. }
  428. removeFile(file);
  429. updateTotalProgress();
  430. });
  431. uploader.on('filesQueued', function (file) {
  432. if (!uploader.isInProgress() && (state == 'pedding' || state == 'finish' || state == 'confirm' || state == 'ready')) {
  433. setState('ready');
  434. }
  435. updateTotalProgress();
  436. });
  437. uploader.on('all', function (type, files) {
  438. switch (type) {
  439. case 'uploadFinished':
  440. setState('confirm', files);
  441. break;
  442. case 'startUpload':
  443. /* 添加额外的GET参数 */
  444. var params = utils.serializeParam(editor.queryCommandValue('serverparam')) || '',
  445. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?' : '&') + 'encode=utf-8&' + params);
  446. uploader.option('server', url);
  447. setState('uploading', files);
  448. break;
  449. case 'stopUpload':
  450. setState('paused', files);
  451. break;
  452. }
  453. });
  454. uploader.on('uploadBeforeSend', function (file, data, header) {
  455. //这里可以通过data对象添加POST参数
  456. if (actionUrl.toLowerCase().indexOf('jsp') != -1) {
  457. header['X_Requested_With'] = 'XMLHttpRequest';
  458. }
  459. });
  460. uploader.on('uploadProgress', function (file, percentage) {
  461. var $li = $('#' + file.id),
  462. $percent = $li.find('.progress span');
  463. $percent.css('width', percentage * 100 + '%');
  464. percentages[file.id][1] = percentage;
  465. updateTotalProgress();
  466. });
  467. uploader.on('uploadSuccess', function (file, ret) {
  468. var $file = $('#' + file.id);
  469. try {
  470. var responseText = (ret._raw || ret),
  471. json = utils.str2json(responseText);
  472. json = editor.getOpt('serverResponsePrepare')(json);
  473. if (json.state == 'SUCCESS') {
  474. _this.fileList.push(json);
  475. $file.append('<span class="success"></span>');
  476. // 触发上传附件事件
  477. editor.fireEvent("uploadsuccess", {
  478. res: json,
  479. type: 'file'
  480. });
  481. } else {
  482. $file.find('.error').text(json.state).show();
  483. }
  484. } catch (e) {
  485. $file.find('.error').text(lang.errorServerUpload).show();
  486. }
  487. });
  488. uploader.on('uploadError', function (file, code) {
  489. });
  490. uploader.on('error', function (code, param1, param2) {
  491. if (code === 'F_EXCEED_SIZE') {
  492. editor.getOpt('tipError')(lang.errorExceedSize + ' ' + (param1 / 1024 / 1024).toFixed(1) + 'MB');
  493. } else {
  494. console.log('error', code, param1, param2);
  495. }
  496. });
  497. uploader.on('uploadComplete', function (file, ret) {
  498. });
  499. $upload.on('click', function () {
  500. if ($(this).hasClass('disabled')) {
  501. return false;
  502. }
  503. if (state === 'ready') {
  504. uploader.upload();
  505. } else if (state === 'paused') {
  506. uploader.upload();
  507. } else if (state === 'uploading') {
  508. uploader.stop();
  509. }
  510. });
  511. $upload.addClass('state-' + state);
  512. updateTotalProgress();
  513. },
  514. getQueueCount: function () {
  515. var file, i, status, readyFile = 0, files = this.uploader.getFiles();
  516. for (i = 0; file = files[i++];) {
  517. status = file.getStatus();
  518. if (status == 'queued' || status == 'uploading' || status == 'progress') readyFile++;
  519. }
  520. return readyFile;
  521. },
  522. getInsertList: function () {
  523. var i, link, data, list = [],
  524. prefix = editor.getOpt('fileUrlPrefix');
  525. for (i = 0; i < this.fileList.length; i++) {
  526. data = this.fileList[i];
  527. link = data.url;
  528. list.push({
  529. title: data.original || link.substr(link.lastIndexOf('/') + 1),
  530. url: prefix + link
  531. });
  532. }
  533. return list;
  534. }
  535. };
  536. /* 在线附件 */
  537. function OnlineFile(target) {
  538. this.container = utils.isString(target) ? document.getElementById(target) : target;
  539. this.init();
  540. }
  541. OnlineFile.prototype = {
  542. init: function () {
  543. this.initContainer();
  544. this.initEvents();
  545. this.initData();
  546. },
  547. /* 初始化容器 */
  548. initContainer: function () {
  549. this.container.innerHTML = '';
  550. this.list = document.createElement('ul');
  551. this.clearFloat = document.createElement('li');
  552. domUtils.addClass(this.list, 'list');
  553. domUtils.addClass(this.clearFloat, 'clearFloat');
  554. this.list.appendChild(this.clearFloat);
  555. this.container.appendChild(this.list);
  556. },
  557. /* 初始化滚动事件,滚动到地步自动拉取数据 */
  558. initEvents: function () {
  559. var _this = this;
  560. /* 滚动拉取图片 */
  561. domUtils.on($G('fileList'), 'scroll', function (e) {
  562. var panel = this;
  563. if (panel.scrollHeight - (panel.offsetHeight + panel.scrollTop) < 10) {
  564. _this.getFileData();
  565. }
  566. });
  567. /* 选中图片 */
  568. domUtils.on(this.list, 'click', function (e) {
  569. var target = e.target || e.srcElement,
  570. li = target.parentNode;
  571. if (li.tagName.toLowerCase() == 'li') {
  572. if (domUtils.hasClass(li, 'selected')) {
  573. domUtils.removeClasses(li, 'selected');
  574. } else {
  575. domUtils.addClass(li, 'selected');
  576. }
  577. }
  578. });
  579. },
  580. /* 初始化第一次的数据 */
  581. initData: function () {
  582. /* 拉取数据需要使用的值 */
  583. this.state = 0;
  584. this.listSize = editor.getOpt('fileManagerListSize');
  585. this.listIndex = 0;
  586. this.listEnd = false;
  587. /* 第一次拉取数据 */
  588. this.getFileData();
  589. },
  590. /* 向后台拉取图片列表数据 */
  591. getFileData: function () {
  592. var _this = this;
  593. if (!_this.listEnd && !this.isLoadingData) {
  594. this.isLoadingData = true;
  595. ajax.request(editor.getActionUrl(editor.getOpt('fileManagerActionName')), {
  596. timeout: 100000,
  597. data: utils.extend({
  598. start: this.listIndex,
  599. size: this.listSize
  600. }, editor.queryCommandValue('serverparam')),
  601. headers: editor.options.serverHeaders || {},
  602. method: 'get',
  603. onsuccess: function (r) {
  604. try {
  605. var json = eval('(' + r.responseText + ')');
  606. if (json.state == 'SUCCESS') {
  607. _this.pushData(json.list);
  608. _this.listIndex = parseInt(json.start) + parseInt(json.list.length);
  609. if (_this.listIndex >= json.total) {
  610. _this.listEnd = true;
  611. }
  612. _this.isLoadingData = false;
  613. }
  614. } catch (e) {
  615. if (r.responseText.indexOf('ue_separate_ue') != -1) {
  616. var list = r.responseText.split(r.responseText);
  617. _this.pushData(list);
  618. _this.listIndex = parseInt(list.length);
  619. _this.listEnd = true;
  620. _this.isLoadingData = false;
  621. }
  622. }
  623. },
  624. onerror: function () {
  625. _this.isLoadingData = false;
  626. }
  627. });
  628. }
  629. },
  630. /* 添加图片到列表界面上 */
  631. pushData: function (list) {
  632. var i, item, img, filetype, preview, icon, _this = this,
  633. urlPrefix = editor.getOpt('fileManagerUrlPrefix');
  634. for (i = 0; i < list.length; i++) {
  635. if (list[i] && list[i].url) {
  636. item = document.createElement('li');
  637. icon = document.createElement('span');
  638. filetype = list[i].url.substr(list[i].url.lastIndexOf('.') + 1);
  639. if ("png|jpg|jpeg|gif|bmp".indexOf(filetype) != -1) {
  640. preview = document.createElement('img');
  641. domUtils.on(preview, 'load', (function (image) {
  642. return function () {
  643. _this.scale(image, image.parentNode.offsetWidth, image.parentNode.offsetHeight);
  644. };
  645. })(preview));
  646. preview.width = 113;
  647. preview.setAttribute('src', urlPrefix + list[i].url + (list[i].url.indexOf('?') == -1 ? '?noCache=' : '&noCache=') + (+new Date()).toString(36));
  648. } else {
  649. var ic = document.createElement('i'),
  650. textSpan = document.createElement('span');
  651. textSpan.innerHTML = list[i].original || list[i].url.substr(list[i].url.lastIndexOf('/') + 1);
  652. preview = document.createElement('div');
  653. preview.appendChild(ic);
  654. preview.appendChild(textSpan);
  655. domUtils.addClass(preview, 'file-wrapper');
  656. domUtils.addClass(textSpan, 'file-title');
  657. domUtils.addClass(ic, 'file-type-' + filetype);
  658. domUtils.addClass(ic, 'file-preview');
  659. }
  660. domUtils.addClass(icon, 'icon');
  661. item.setAttribute('data-url', urlPrefix + list[i].url);
  662. if (list[i].original) {
  663. item.setAttribute('data-title', list[i].original);
  664. }
  665. item.appendChild(preview);
  666. item.appendChild(icon);
  667. this.list.insertBefore(item, this.clearFloat);
  668. }
  669. }
  670. },
  671. /* 改变图片大小 */
  672. scale: function (img, w, h, type) {
  673. var ow = img.width,
  674. oh = img.height;
  675. if (type == 'justify') {
  676. if (ow >= oh) {
  677. img.width = w;
  678. img.height = h * oh / ow;
  679. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  680. } else {
  681. img.width = w * ow / oh;
  682. img.height = h;
  683. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  684. }
  685. } else {
  686. if (ow >= oh) {
  687. img.width = w * ow / oh;
  688. img.height = h;
  689. img.style.marginLeft = '-' + parseInt((img.width - w) / 2) + 'px';
  690. } else {
  691. img.width = w;
  692. img.height = h * oh / ow;
  693. img.style.marginTop = '-' + parseInt((img.height - h) / 2) + 'px';
  694. }
  695. }
  696. },
  697. getInsertList: function () {
  698. var i, lis = this.list.children, list = [];
  699. for (i = 0; i < lis.length; i++) {
  700. if (domUtils.hasClass(lis[i], 'selected')) {
  701. var url = lis[i].getAttribute('data-url');
  702. var title = lis[i].getAttribute('data-title') || url.substr(url.lastIndexOf('/') + 1);
  703. list.push({
  704. title: title,
  705. url: url
  706. });
  707. }
  708. }
  709. return list;
  710. }
  711. };
  712. })();