56d7b7c0be2f27485385873ead3424194afe7440.svn-base 35 KB

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