upload.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. (function (w, $) {
  2. function Uploader(opts) {
  3. opts = $.extend({
  4. wrapper: '.web-uploader', // 图片显示容器选择器
  5. addFileButton: '.add-file-button', // 继续添加按钮选择器
  6. isImage: false,
  7. preview: [], // 数据预览
  8. server: '',
  9. updateServer: '',
  10. sortable: false,
  11. deleteUrl: '',
  12. deleteData: {},
  13. thumbHeight: 160,
  14. disabled: false, // 禁止任何上传编辑
  15. autoUpdateColumn: false,
  16. disableRemove: false, // 禁止删除图片,允许替换
  17. dimensions: {
  18. // width: 100, // 图片宽限制
  19. // height: 100, // 图片高限制
  20. // min_width: 100, //
  21. // min_height: 100,
  22. // max_width: 100,
  23. // max_height: 100,
  24. // ratio: 3/2, // 宽高比
  25. },
  26. lang: {
  27. exceed_size: '文件大小超出',
  28. interrupt: '上传暂停',
  29. upload_failed: '上传失败,请重试',
  30. selected_files: '选中:num个文件,共:size。',
  31. selected_has_failed: '已成功上传:success个文件,:fail个文件上传失败,<a class="retry" href="javascript:"";">重新上传</a>失败文件或<a class="ignore" href="javascript:"";">忽略</a>',
  32. selected_success: '共:num个(:size),已上传:success个。',
  33. dot: ',',
  34. failed_num: '失败:fail个。',
  35. pause_upload: '暂停上传',
  36. go_on_upload: '继续上传',
  37. start_upload: '开始上传',
  38. upload_success_message: '已成功上传:success个文件',
  39. go_on_add: '继续添加',
  40. Q_TYPE_DENIED: '对不起,不允许上传此类型文件',
  41. Q_EXCEED_NUM_LIMIT: '对不起,已超出文件上传数量限制,最多只能上传:num个文件',
  42. F_EXCEED_SIZE: '对不起,当前选择的文件过大',
  43. Q_EXCEED_SIZE_LIMIT: '对不起,已超出文件大小限制',
  44. F_DUPLICATE: '文件重复',
  45. confirm_delete_file: '您确定要删除这个文件吗?',
  46. },
  47. upload: { // web-uploader配置
  48. formData: {
  49. _id: null, // 唯一id
  50. },
  51. thumb: {
  52. width: 160,
  53. height: 160,
  54. quality: 70,
  55. allowMagnify: true,
  56. crop: true,
  57. preserveHeaders: false,
  58. // 为空的话则保留原有图片格式。
  59. // 否则强制转换成指定的类型。
  60. // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可
  61. // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
  62. type: 'image/jpeg'
  63. },
  64. }
  65. }, opts);
  66. var $selector = $(opts.selector),
  67. updateColumn = opts.upload.formData.upload_column || ('webup' + Math.floor(Math.random()*10000)),
  68. elementName = opts.elementName;
  69. if (typeof opts.upload.formData._id == "undefined" || !opts.upload.formData._id) {
  70. opts.upload.formData._id = updateColumn + Math.floor(Math.random()*10000);
  71. }
  72. let Dcat = w.Dcat,
  73. $wrap,
  74. // 展示图片
  75. showImg = opts.isImage,
  76. // 图片容器
  77. $queue,
  78. // 状态栏,包括进度和控制按钮
  79. $statusBar,
  80. // 文件总体选择信息。
  81. $info,
  82. // 上传按钮
  83. $upload,
  84. // 没选择文件之前的内容。
  85. $placeHolder,
  86. $progress,
  87. // 已上传文件数量
  88. originalFilesNum = Dcat.helpers.len(opts.preview),
  89. // 上传表单
  90. $input = $selector.find('input[name="' + elementName + '"]'),
  91. // 获取文件视图选择器
  92. getFileViewSelector = function (fileId) {
  93. return elementName.replace(/[\[\]]*/g, '_')+'-'+fileId;
  94. },
  95. getFileView = function (fileId) {
  96. return $('#' + getFileViewSelector(fileId));
  97. },
  98. // 继续添加按钮选择器
  99. addFileButtonSelector = opts.addFileButton,
  100. // 临时存储上传失败的文件,key为file id
  101. faildFiles = {},
  102. // 临时存储添加到form表单的文件
  103. formFiles = {},
  104. // 添加的文件数量
  105. fileCount = 0,
  106. // 添加的文件总大小
  107. fileSize = 0,
  108. // 可能有pedding, ready, uploading, confirm, done.
  109. state = 'pedding',
  110. // 所有文件的进度信息,key为file id
  111. percentages = {},
  112. // 判断浏览器是否支持图片的base64
  113. isSupportBase64 = (function () {
  114. var data = new Image();
  115. var support = true;
  116. data.onload = data.onerror = function () {
  117. if (this.width != 1 || this.height != 1) {
  118. support = false;
  119. }
  120. };
  121. data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
  122. return support;
  123. })(),
  124. // 检测是否已经安装flash,检测flash的版本
  125. flashVersion = (function () {
  126. var version;
  127. try {
  128. version = navigator.plugins['Shockwave Flash'];
  129. version = version.description;
  130. } catch (ex) {
  131. try {
  132. version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
  133. .GetVariable('$version');
  134. } catch (ex2) {
  135. version = '0.0';
  136. }
  137. }
  138. version = version.match(/\d+/g);
  139. return parseFloat(version[0] + '.' + version[1], 10);
  140. })(),
  141. // 判断是否是图片
  142. isImage = function (file) {
  143. return file.type.match(/^image/);
  144. },
  145. // 翻译
  146. lang = Dcat.Translator(opts.lang),
  147. __ = lang.trans.bind(lang),
  148. // WebUploader实例
  149. uploader,
  150. // 已上传的文件
  151. uploadedFiles = [],
  152. initImg;
  153. // 当有文件添加进来时执行,负责view的创建
  154. function addFile(file) {
  155. var size = WebUploader.formatSize(file.size), $li, $btns, fileName = file.name || null;
  156. if (showImg) {
  157. $li = $(`<li id="${getFileViewSelector(file.id)}" title="${fileName}" >
  158. <p class="file-type">${(file.ext.toUpperCase() || 'FILE')}</p>
  159. <p class="imgWrap "></p>
  160. <p class="title" style="">${file.name}</p>
  161. <p class="title" style="margin-bottom:20px;">(<b>${size}</b>)</p>
  162. </li>`);
  163. $btns = $(`<div class="file-panel">
  164. <a class="btn btn-sm btn-white" data-file-act="cancel"><i class="feather icon-x red-dark" style="font-size:13px"></i></a>
  165. <a class="btn btn-sm btn-white" data-file-act="delete" style="display: none">
  166. <i class="feather icon-trash red-dark" style="font-size:13px"></i></a>
  167. <a class="btn btn-sm btn-white" data-file-act="preview" ><i class="feather icon-zoom-in"></i></a>
  168. <a class='btn btn-sm btn-white' data-file-act='order' data-order="1" style="display: none"><i class='feather icon-arrow-up'></i></a>
  169. <a class='btn btn-sm btn-white' data-file-act='order' data-order="0" style="display: none"><i class='feather icon-arrow-down'></i></a>
  170. </div>`).appendTo($li);
  171. } else {
  172. $li = $(`
  173. <li id="${getFileViewSelector(file.id)}" title="${file.nam}">
  174. <p class="title" style="display:block">
  175. <i class="feather icon-check green _success icon-success"></i>
  176. ${file.name} (${size})
  177. </p>
  178. </li>
  179. `);
  180. $btns = $(`
  181. <span style="right: 45px;" class="file-action d-none" data-file-act='order' data-order="1"><i class='feather icon-arrow-up'></i></span>
  182. <span style="right: 25px;" class="file-action d-none" data-file-act='order' data-order="0"><i class='feather icon-arrow-down'></i></span>
  183. <span data-file-act="cancel" class="file-action" style="font-size:13px">
  184. <i class="feather icon-x red-dark"></i>
  185. </span>
  186. <span data-file-act="delete" class="file-action" style="display:none">
  187. <i class="feather icon-trash red-dark"></i>
  188. </span>
  189. `).appendTo($li);
  190. }
  191. var $wrap = $li.find('p.imgWrap'),
  192. $info = $('<p class="error"></p>'),
  193. showError = function (code, file) {
  194. var text = '';
  195. switch (code) {
  196. case 'exceed_size':
  197. text = __('exceed_size');
  198. break;
  199. case 'interrupt':
  200. text = __('interrupt');
  201. break;
  202. default:
  203. text = __('upload_failed');
  204. break;
  205. }
  206. faildFiles[file.id] = file;
  207. $info.text(text).appendTo($li);
  208. };
  209. $li.appendTo($queue);
  210. setTimeout(function () {
  211. $li.css({margin: '5px'});
  212. }, 50);
  213. if (file.getStatus() === 'invalid') {
  214. showError(file.statusText, file);
  215. } else {
  216. if (showImg) {
  217. var image = uploader.makeThumb(file, function (error, src) {
  218. var img;
  219. $wrap.empty();
  220. if (error) {
  221. $li.find('.title').show();
  222. $li.find('.file-type').show();
  223. return;
  224. }
  225. if (isSupportBase64) {
  226. img = $('<img src="' + src + '">');
  227. $wrap.append(img);
  228. } else {
  229. $li.find('.file-type').show();
  230. }
  231. });
  232. try {
  233. image.once('load', function () {
  234. file._info = file._info || image.info();
  235. file._meta = file._meta || image.meta();
  236. var width = file._info.width,
  237. height = file._info.height;
  238. if (!validateDimensions(file)) {
  239. Dcat.error('The image dimensions is invalid.');
  240. uploader.removeFile(file);
  241. return false;
  242. }
  243. image.resize(width, height);
  244. });
  245. } catch (e) {
  246. // 不是图片
  247. return setTimeout(function () {
  248. uploader.removeFile(file);
  249. }, 10);
  250. }
  251. }
  252. percentages[file.id] = [file.size, 0];
  253. file.rotation = 0;
  254. }
  255. file.on('statuschange', function (cur, prev) {
  256. if (prev === 'progress') {
  257. // $prgress.hide().width(0);
  258. } else if (prev === 'queued') {
  259. $btns.find('[data-file-act="cancel"]').hide();
  260. $btns.find('[data-file-act="delete"]').show();
  261. }
  262. // 成功
  263. if (cur === 'error' || cur === 'invalid') {
  264. showError(file.statusText, file);
  265. percentages[file.id][1] = 1;
  266. } else if (cur === 'interrupt') {
  267. showError('interrupt', file);
  268. } else if (cur === 'queued') {
  269. percentages[file.id][1] = 0;
  270. } else if (cur === 'progress') {
  271. $info.remove();
  272. // $prgress.css('display', 'block');
  273. } else if (cur === 'complete') {
  274. if (showImg) {
  275. $li.append('<span class="success"><em></em><i class="feather icon-check"></i></span>');
  276. } else {
  277. $li.find('._success').show();
  278. }
  279. }
  280. $li.removeClass('state-' + prev).addClass('state-' + cur);
  281. });
  282. var $act = showImg ? $btns.find('a') : $btns;
  283. $act.on('click', function () {
  284. var index = $(this).data('file-act');
  285. switch (index) {
  286. case 'cancel':
  287. uploader.removeFile(file);
  288. return;
  289. case 'deleteurl':
  290. case 'delete':
  291. if (opts.disableRemove) {
  292. deleteInput(file.serverId);
  293. return uploader.removeFile(file);
  294. }
  295. Dcat.confirm(__('confirm_delete_file'), file.serverId, function () {
  296. var post = opts.deleteData;
  297. post.key = file.serverId;
  298. if (!post.key) {
  299. deleteInput(file.serverId);
  300. return uploader.removeFile(file);
  301. }
  302. post._column = updateColumn;
  303. Dcat.loading();
  304. $.post(opts.deleteUrl, post, function (result) {
  305. Dcat.loading(false);
  306. if (result.status) {
  307. deleteInput(file.serverId);
  308. uploader.removeFile(file);
  309. return;
  310. }
  311. Dcat.error(result.message || 'Remove file failed.');
  312. });
  313. });
  314. break;
  315. case 'preview':
  316. Dcat.helpers.previewImage($wrap.find('img').attr('src'), null, file.name);
  317. break;
  318. case 'order':
  319. $(this).attr('data-id', file.serverId);
  320. orderFiles.apply(this);
  321. break;
  322. }
  323. });
  324. }
  325. // 图片宽高验证
  326. function validateDimensions(file) {
  327. // The image dimensions is invalid.
  328. if (!showImg || !isImage(file) || !Dcat.helpers.len(opts.dimensions)) return true;
  329. var dimensions = opts.dimensions,
  330. width = file._info.width,
  331. height = file._info.height,
  332. isset = Dcat.helpers.isset;
  333. if (
  334. (isset(dimensions, 'width') && dimensions['width'] != width) ||
  335. (isset(dimensions, 'min_width') && dimensions['min_width'] > width)||
  336. (isset(dimensions, 'max_width') && dimensions['max_width'] < width) ||
  337. (isset(dimensions, 'height') && dimensions['height'] != height) ||
  338. (isset(dimensions, 'min_height') && dimensions['min_height'] > height) ||
  339. (isset(dimensions, 'max_height') && dimensions['max_height'] < height) ||
  340. (isset(dimensions, 'ratio') && dimensions['ratio'] != (width / height))
  341. ) {
  342. return false;
  343. }
  344. return true;
  345. }
  346. // 负责view的销毁
  347. function removeUploadFile(file) {
  348. var $li = getFileView(file.id);
  349. delete percentages[file.id];
  350. updateTotalProgress();
  351. $li.off().find('.file-panel').off().end().remove();
  352. }
  353. function updateTotalProgress() {
  354. var loaded = 0,
  355. total = 0,
  356. $bar = $progress.find('.progress-bar'),
  357. percent;
  358. $.each(percentages, function (k, v) {
  359. total += v[0];
  360. loaded += v[0] * v[1];
  361. });
  362. percent = total ? loaded / total : 0;
  363. percent = Math.round(percent * 100) + '%';
  364. $bar.text(percent);
  365. $bar.css('width', percent);
  366. updateStatusText();
  367. }
  368. function updateStatusText() {
  369. var text = '', stats;
  370. if (!uploader) {
  371. return;
  372. }
  373. if (state === 'ready') {
  374. stats = uploader.getStats();
  375. if (fileCount) {
  376. text = __('selected_files', {num: fileCount, size: WebUploader.formatSize(fileSize)});
  377. } else {
  378. showSuccess();
  379. }
  380. } else if (state === 'confirm') {
  381. stats = uploader.getStats();
  382. if (stats.uploadFailNum) {
  383. text = __('selected_has_failed', {success: stats.successNum, fail: stats.uploadFailNum});
  384. }
  385. } else {
  386. showSuccess();
  387. }
  388. function showSuccess() {
  389. stats = uploader.getStats();
  390. if (stats.successNum) {
  391. text = __('selected_success', {num: fileCount, size: WebUploader.formatSize(fileSize), success: stats.successNum});
  392. }
  393. if (stats.uploadFailNum) {
  394. text += (text ? __('dot') : '') + __('failed_num', {fail: stats.uploadFailNum});
  395. }
  396. }
  397. $info.html(text);
  398. }
  399. // 上传文件后修改字段值
  400. function updateFileColumn() {
  401. var values = getInput(),
  402. num = uploader.getStats().successNum,
  403. form = $.extend({}, opts.formData);
  404. if (!num || !values || !opts.autoUpdateColumn) {
  405. return;
  406. }
  407. form[updateColumn] = values.join(',');
  408. delete form['upload_column'];
  409. $.post(opts.updateServer, form);
  410. }
  411. function setState(val, args) {
  412. var stats;
  413. args = args || {};
  414. if (val === state) {
  415. return;
  416. }
  417. if ($upload) {
  418. $upload.removeClass('state-' + state);
  419. $upload.addClass('state-' + val);
  420. }
  421. state = val;
  422. switch (state) {
  423. case 'pedding':
  424. if (opts.disabled) return;
  425. $placeHolder.removeClass('element-invisible');
  426. $queue.hide();
  427. $statusBar.addClass('element-invisible');
  428. if (showImg) {
  429. $wrap.removeAttr('style');
  430. $wrap.find('.queueList').removeAttr('style');
  431. }
  432. refreshButton();
  433. break;
  434. case 'ready':
  435. $placeHolder.addClass('element-invisible');
  436. $selector.find(addFileButtonSelector).removeClass('element-invisible');
  437. $queue.show();
  438. if (!opts.disabled) {
  439. $statusBar.removeClass('element-invisible');
  440. }
  441. refreshButton();
  442. if (showImg) {
  443. $wrap.find('.queueList').css({'border': '1px solid #d3dde5', 'padding':'5px'});
  444. // $wrap.find('.queueList').removeAttr('style');
  445. }
  446. break;
  447. case 'uploading':
  448. $selector.find(addFileButtonSelector).addClass('element-invisible');
  449. $progress.show();
  450. $upload.text(__('pause_upload'));
  451. break;
  452. case 'paused':
  453. $progress.show();
  454. $upload.text(__('go_on_upload'));
  455. break;
  456. case 'confirm':
  457. if (uploader) {
  458. $progress.hide();
  459. $selector.find(addFileButtonSelector).removeClass('element-invisible');
  460. $upload.text(__('start_upload'));
  461. stats = uploader.getStats();
  462. if (stats.successNum && !stats.uploadFailNum) {
  463. setState('finish');
  464. return;
  465. }
  466. }
  467. break;
  468. case 'finish':
  469. if (uploader) {
  470. stats = uploader.getStats();
  471. if (stats.successNum) {
  472. Dcat.success(__('upload_success_message', {success: stats.successNum}));
  473. setTimeout(function () {
  474. if (opts.upload.fileNumLimit == 1) {
  475. // 单文件上传,需要重置文件上传个数
  476. uploader.request('get-stats').numOfSuccess = 0;
  477. }
  478. }, 10);
  479. } else {
  480. // 没有成功的图片,重设
  481. state = 'done';
  482. location.reload();
  483. }
  484. }
  485. break;
  486. case 'decrOriginalFileNum':
  487. if (originalFilesNum > 0) originalFilesNum --;
  488. break;
  489. case 'incrOriginalFileNum':
  490. originalFilesNum ++;
  491. break;
  492. case 'decrFileNumLimit': // 减少上传文件数量限制
  493. if (!uploader) {
  494. return;
  495. }
  496. var fileLimit = uploader.option('fileNumLimit'),
  497. num = args.num || 1;
  498. if (fileLimit == '-1') fileLimit = 0;
  499. num = fileLimit >= num ? fileLimit - num : 0;
  500. if (num == 0) num = '-1';
  501. uploader.option('fileNumLimit', num);
  502. break;
  503. case 'incrFileNumLimit': // 增加上传文件数量限制
  504. if (!uploader) {
  505. return;
  506. }
  507. var fileLimit = uploader.option('fileNumLimit'),
  508. num = args.num || 1;
  509. if (fileLimit == '-1') fileLimit = 0;
  510. num = fileLimit + num;
  511. uploader.option('fileNumLimit', num);
  512. break;
  513. case 'init': // 初始化
  514. $upload.addClass('state-' + state);
  515. updateTotalProgress();
  516. if (originalFilesNum || opts.disabled) {
  517. $placeHolder.addClass('element-invisible');
  518. if (!opts.disabled) {
  519. $statusBar.show();
  520. } else {
  521. $wrap.addClass('disabled');
  522. }
  523. setState('ready');
  524. } else if (showImg) {
  525. $wrap.removeAttr('style');
  526. $wrap.find('.queueList').css('margin', '0');
  527. }
  528. refreshButton();
  529. break;
  530. }
  531. updateStatusText();
  532. }
  533. // 移除form表单的文件
  534. function removeFormFile(fileId) {
  535. if (!fileId) return;
  536. var file = formFiles[fileId];
  537. deleteInput(fileId);
  538. delete formFiles[fileId];
  539. if (uploader && !file.fake) {
  540. uploader.removeFile(file);
  541. }
  542. setState('decrOriginalFileNum');
  543. setState('incrFileNumLimit');
  544. if (!Dcat.helpers.len(formFiles) && !Dcat.helpers.len(percentages)) {
  545. setState('pedding');
  546. }
  547. }
  548. // 获取表单值
  549. function getInput() {
  550. var val = $input.val();
  551. return val ? val.split(',') : [];
  552. }
  553. // 新增表单值
  554. function addInput(id) {
  555. var val = getInput();
  556. val.push(id);
  557. setInput(val);
  558. }
  559. // 设置表单值
  560. function setInput(arr) {
  561. arr = arr.filter(function(v, k, self) {
  562. return self.indexOf(v) === k;
  563. }).filter(function (v) {
  564. return v ? true : false;
  565. });
  566. $input.val(arr.join(','));
  567. }
  568. // 删除表单值
  569. function deleteInput(id) {
  570. deleteUploadedFile(id);
  571. if (!id) {
  572. return $input.val('');
  573. }
  574. setInput(getInput().filter(function (v) {
  575. return v != id;
  576. }));
  577. }
  578. // 添加已上传文件
  579. function appendUploadedFile(file) {
  580. if (! file.serverId || searchUploadedFile(file.serverId) !== -1) {
  581. return;
  582. }
  583. uploadedFiles.push(file)
  584. }
  585. function syncUploadedFiles() {
  586. var files = [];
  587. for (var i in uploadedFiles) {
  588. if (uploadedFiles[i]) {
  589. files.push(uploadedFiles[i].serverId);
  590. }
  591. }
  592. setInput(files);
  593. }
  594. function deleteUploadedFile(fileId) {
  595. uploadedFiles = uploadedFiles.filter(function (v) {
  596. return v.serverId != fileId;
  597. });
  598. }
  599. // 查找文件位置
  600. function searchUploadedFile(fileId) {
  601. for (var i in uploadedFiles) {
  602. if (uploadedFiles[i].serverId === fileId) {
  603. return i;
  604. }
  605. }
  606. return -1;
  607. }
  608. // 交换文件排序
  609. function swrapUploadedFile(fileId, order) {
  610. var index = parseInt(searchUploadedFile(fileId)),
  611. currentFile = uploadedFiles[index],
  612. prevFile = uploadedFiles[index - 1],
  613. nextFile = uploadedFiles[index + 1];
  614. if (order) {
  615. if (index === 0) {
  616. return;
  617. }
  618. uploadedFiles[index - 1] = currentFile;
  619. uploadedFiles[index] = prevFile;
  620. } else {
  621. if (! nextFile) {
  622. return;
  623. }
  624. uploadedFiles[index + 1] = currentFile;
  625. uploadedFiles[index] = nextFile;
  626. }
  627. syncUploadedFiles();
  628. }
  629. // 重新渲染已上传文件
  630. function rerenderUploadedFiles() {
  631. $queue.html('');
  632. for (var i in uploadedFiles) {
  633. if (uploadedFiles[i]) {
  634. appendUploadedFileForm(uploadedFiles[i])
  635. }
  636. }
  637. }
  638. // 重新计算按钮定位
  639. function refreshButton() {
  640. uploader.refresh();
  641. }
  642. // 文件排序
  643. function orderFiles() {
  644. var $this = $(this),
  645. $li = $this.parents('li').first(),
  646. fileId = $this.data('id'),
  647. order = $this.data('order'),
  648. $prev = $li.prev(),
  649. $next = $li.next();
  650. if (order) {
  651. // 升序
  652. if (! $prev.length) {
  653. return;
  654. }
  655. swrapUploadedFile(fileId, order);
  656. rerenderUploadedFiles();
  657. return;
  658. }
  659. if (! $next.length) {
  660. return;
  661. }
  662. swrapUploadedFile(fileId, order);
  663. rerenderUploadedFiles();
  664. }
  665. // 添加上传成功文件到表单区域
  666. function appendUploadedFileForm(file) {
  667. var html = "";
  668. html += "<li title='" + file.serverPath + "'>";
  669. if (! showImg && opts.sortable) {
  670. // 文件排序
  671. html += `
  672. <p style="right: 45px" class="file-action" data-file-act='order' data-order="1" data-id='${file.serverId}'><i class='feather icon-arrow-up'></i></p>
  673. <p style="right: 25px" class="file-action" data-file-act='order' data-order="0" data-id='${file.serverId}'><i class='feather icon-arrow-down'></i></p>
  674. `;
  675. }
  676. if (showImg) {
  677. html += `<p class='imgWrap'><img src='${file.serverUrl}'></p>`
  678. } else if (! opts.disabled) {
  679. html += `<p class="file-action" data-file-act="delete" data-id="${file.serverId}"><i class="feather icon-trash red-dark"></i></p>`;
  680. }
  681. html += "<p class='title' style=''><i class='feather icon-check text-white icon-success text-white'></i>";
  682. html += file.serverPath;
  683. html += "</p>";
  684. if (showImg) {
  685. html += "<p class='title' style='margin-bottom:20px;'>&nbsp;</p>";
  686. html += "<div class='file-panel' >";
  687. if (! opts.disabled) {
  688. html += `<a class='btn btn-sm btn-white' data-file-act='deleteurl' data-id='${file.serverId}'><i class='feather icon-trash red-dark' style='font-size:13px'></i></a>`;
  689. }
  690. html += `<a class='btn btn-sm btn-white' data-file-act='preview' data-url='${file.serverUrl}' ><i class='feather icon-zoom-in'></i></a>`;
  691. if (opts.sortable) {
  692. // 文件排序
  693. html += `
  694. <a class='btn btn-sm btn-white' data-file-act='order' data-order="1" data-id='${file.serverId}'><i class='feather icon-arrow-up'></i></a>
  695. <a class='btn btn-sm btn-white' data-file-act='order' data-order="0" data-id='${file.serverId}'><i class='feather icon-arrow-down'></i></a>
  696. `;
  697. }
  698. html += "</div>";
  699. } else {
  700. }
  701. html += "</li>";
  702. html = $(html);
  703. if (!showImg) {
  704. html.find('.file-type').show();
  705. html.find('.title').show();
  706. $wrap.css('background', 'transparent');
  707. }
  708. var deleteFile = function () {
  709. var fileId = $(this).data('id'), post = opts.deleteData;
  710. if (opts.disableRemove) {
  711. html.remove();
  712. return removeFormFile(fileId);
  713. }
  714. Dcat.confirm(__('confirm_delete_file'), file.serverId, function () {
  715. post.key = fileId;
  716. post._column = updateColumn;
  717. Dcat.loading();
  718. $.post(opts.deleteUrl, post, function (result) {
  719. Dcat.loading(false);
  720. if (result.status) {
  721. // 移除
  722. html.remove();
  723. removeFormFile(fileId);
  724. return;
  725. }
  726. Dcat.error(result.message || 'Remove file failed.')
  727. });
  728. });
  729. };
  730. // 删除按钮点击事件
  731. html.find('[data-file-act="deleteurl"]').click(deleteFile);
  732. html.find('[data-file-act="delete"]').click(deleteFile);
  733. // 文件排序
  734. if (opts.sortable) {
  735. html.find('[data-file-act="order"').click(orderFiles);
  736. }
  737. // 放大图片
  738. html.find('[data-file-act="preview"]').click(function () {
  739. var url = $(this).data('url');
  740. Dcat.helpers.previewImage(url);
  741. });
  742. formFiles[file.serverId] = file;
  743. addInput(file.serverId);
  744. $queue.append(html);
  745. if (showImg) {
  746. setTimeout(function () {
  747. html.css('margin', '5px');
  748. }, initImg ? 0 : 400);
  749. initImg = 1;
  750. }
  751. }
  752. // 初始化web-uploader
  753. function build() {
  754. $wrap = $selector.find(opts.wrapper);
  755. // 图片容器
  756. $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList'));
  757. // 状态栏,包括进度和控制按钮
  758. $statusBar = $wrap.find('.statusBar');
  759. // 文件总体选择信息。
  760. $info = $statusBar.find('.info');
  761. // 上传按钮
  762. $upload = $wrap.find('.upload-btn');
  763. // 没选择文件之前的内容。
  764. $placeHolder = $wrap.find('.placeholder');
  765. $progress = $statusBar.find('.upload-progress').hide();
  766. // IE;
  767. supportIe();
  768. // 实例化
  769. this.uploader = uploader = WebUploader.create(opts.upload);
  770. // 拖拽时不接受 js, txt 文件。
  771. uploader.on('dndAccept', function (items) {
  772. var denied = false,
  773. len = items.length,
  774. i = 0,
  775. // 修改js类型
  776. unAllowed = 'text/plain;application/javascript ';
  777. for (; i < len; i++) {
  778. // 如果在列表里面
  779. if (~unAllowed.indexOf(items[i].type)) {
  780. denied = true;
  781. break;
  782. }
  783. }
  784. return !denied;
  785. });
  786. if (opts.upload.fileNumLimit > 1 && !opts.disabled) {
  787. // 添加“添加文件”的按钮,
  788. uploader.addButton({
  789. id: addFileButtonSelector,
  790. label: '<i class="feather icon-folder"></i> &nbsp;' + __('go_on_add')
  791. });
  792. }
  793. uploader.onUploadProgress = function (file, percentage) {
  794. percentages[file.id][1] = percentage;
  795. updateTotalProgress();
  796. };
  797. uploader.onBeforeFileQueued = function (file) {
  798. };
  799. // 添加文件
  800. uploader.onFileQueued = function (file) {
  801. fileCount++;
  802. fileSize += file.size;
  803. if (fileCount === 1) {
  804. $placeHolder.addClass('element-invisible');
  805. $statusBar.show();
  806. }
  807. addFile(file);
  808. setState('ready');
  809. updateTotalProgress();
  810. };
  811. // 删除文件事件监听
  812. uploader.onFileDequeued = function (file) {
  813. fileCount--;
  814. fileSize -= file.size;
  815. if (!fileCount && !Dcat.helpers.len(formFiles)) {
  816. setState('pedding');
  817. }
  818. removeUploadFile(file);
  819. };
  820. uploader.on('all', function (type, obj, reason) {
  821. switch (type) {
  822. case 'uploadFinished':
  823. setState('confirm');
  824. updateFileColumn();
  825. break;
  826. case 'startUpload':
  827. setState('uploading');
  828. break;
  829. case 'stopUpload':
  830. setState('paused');
  831. break;
  832. case 'uploadAccept':
  833. // 上传失败,返回false
  834. if (reason && reason.error) {
  835. Dcat.error(reason.error.message);
  836. faildFiles[obj.file.id] = obj.file;
  837. return false;
  838. }
  839. if (reason.merge) {
  840. // 分片上传
  841. return;
  842. }
  843. // 上传成功,保存新文件名和路径到file对象
  844. obj.file.serverId = reason.id;
  845. obj.file.serverName = reason.name;
  846. obj.file.serverPath = reason.path;
  847. obj.file.serverUrl = reason.url || null;
  848. appendUploadedFile(obj.file);
  849. addInput(reason.id);
  850. var $li = getFileView(obj.file.id);
  851. if (!showImg) {
  852. $li.find('.file-action').hide();
  853. $li.find('[data-file-act="delete"]').show();
  854. }
  855. if (opts.sortable) {
  856. $li.find('[data-file-act="order"]').removeClass('d-none').show();
  857. }
  858. break;
  859. }
  860. });
  861. uploader.onError = function (code) {
  862. switch (code) {
  863. case 'Q_TYPE_DENIED':
  864. Dcat.error(__('Q_TYPE_DENIED'));
  865. break;
  866. case 'Q_EXCEED_NUM_LIMIT':
  867. Dcat.error(__('Q_EXCEED_NUM_LIMIT', {num: opts.upload.fileNumLimit}));
  868. break;
  869. case 'F_EXCEED_SIZE':
  870. Dcat.error(__('F_EXCEED_SIZE'));
  871. break;
  872. case 'Q_EXCEED_SIZE_LIMIT':
  873. Dcat.error(__('Q_EXCEED_SIZE_LIMIT'));
  874. break;
  875. case 'F_DUPLICATE':
  876. Dcat.warning(__('F_DUPLICATE'));
  877. break;
  878. default:
  879. Dcat.error('Error: ' + code);
  880. }
  881. };
  882. $upload.on('click', function () {
  883. if ($(this).hasClass('disabled')) {
  884. return false;
  885. }
  886. if (state === 'ready') {
  887. uploader.upload();
  888. } else if (state === 'paused') {
  889. uploader.upload();
  890. } else if (state === 'uploading') {
  891. uploader.stop();
  892. }
  893. });
  894. $info.on('click', '.retry', function () {
  895. uploader.retry();
  896. });
  897. $info.on('click', '.ignore', function () {
  898. for (var i in faildFiles) {
  899. uploader.removeFile(i, true);
  900. delete faildFiles[i];
  901. }
  902. });
  903. setState('init');
  904. }
  905. // 预览
  906. function preview() {
  907. for (var i in opts.preview) {
  908. var path = opts.preview[i].path, ext;
  909. if (path.indexOf('.')) {
  910. ext = path.split('.').pop();
  911. }
  912. var file = {
  913. serverId: opts.preview[i].id,
  914. serverUrl: opts.preview[i].url,
  915. serverPath: path,
  916. ext: ext,
  917. fake: 1,
  918. };
  919. setState('incrOriginalFileNum');
  920. setState('decrFileNumLimit');
  921. appendUploadedFileForm(file);
  922. appendUploadedFile(file);
  923. }
  924. }
  925. this.uploader = uploader;
  926. this.options = opts;
  927. this.build = build;
  928. this.preview = preview;
  929. this.setState = setState;
  930. this.refreshButton = refreshButton;
  931. this.getFileView = getFileView;
  932. this.getFileViewSelector = getFileViewSelector;
  933. this.addFileView = addFile;
  934. this.removeUploadFileView = removeUploadFile;
  935. this.isImage = isImage;
  936. this.getColumn = function () {
  937. return updateColumn;
  938. };
  939. function supportIe() {
  940. if (!WebUploader.Uploader.support('flash') && WebUploader.browser.ie) {
  941. // flash 安装了但是版本过低。
  942. if (flashVersion) {
  943. (function (container) {
  944. window['expressinstallcallback'] = function (state) {
  945. switch (state) {
  946. case 'Download.Cancelled':
  947. break;
  948. case 'Download.Failed':
  949. Dcat.error('Install failed!');
  950. break;
  951. default:
  952. Dcat.success('Install Success!');
  953. break;
  954. }
  955. delete window['expressinstallcallback'];
  956. };
  957. var swf = './expressInstall.swf';
  958. // insert flash object
  959. var html = `<object type="application/x-shockwave-flash" data="${swf}" `;
  960. if (WebUploader.browser.ie) {
  961. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  962. }
  963. html += `width="100%" height="100%" style="outline:0">
  964. <param name="movie" value="${swf}" />
  965. <param name="wmode" value="transparent" />
  966. <param name="allowscriptaccess" value="always" />
  967. </object>`;
  968. container.html(html);
  969. })($wrap);
  970. } else {
  971. $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
  972. }
  973. return;
  974. } else if (!WebUploader.Uploader.support()) {
  975. Dcat.error('您的浏览器不支持Web Uploader!');
  976. return;
  977. }
  978. }
  979. return this;
  980. }
  981. Dcat.Uploader = function (options) {
  982. return new Uploader(options)
  983. };
  984. })(window, jQuery);