attachment.js 33 KB

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