upload.js 44 KB

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