attachment.js 31KB

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