upload.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  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({
  309. url: opts.deleteUrl,
  310. data: post,
  311. success: function (result) {
  312. Dcat.loading(false);
  313. if (result.status) {
  314. deleteInput(file.serverId);
  315. uploader.removeFile(file);
  316. return;
  317. }
  318. Dcat.error(result.message || 'Remove file failed.');
  319. }
  320. });
  321. });
  322. break;
  323. case 'preview':
  324. Dcat.helpers.previewImage($wrap.find('img').attr('src'), null, file.name);
  325. break;
  326. case 'order':
  327. $(this).attr('data-id', file.serverId);
  328. orderFiles.apply(this);
  329. break;
  330. }
  331. });
  332. }
  333. // 图片宽高验证
  334. function validateDimensions(file) {
  335. // The image dimensions is invalid.
  336. if (!showImg || !isImage(file) || !Dcat.helpers.len(opts.dimensions)) return true;
  337. var dimensions = opts.dimensions,
  338. width = file._info.width,
  339. height = file._info.height,
  340. isset = Dcat.helpers.isset;
  341. if (
  342. (isset(dimensions, 'width') && dimensions['width'] != width) ||
  343. (isset(dimensions, 'min_width') && dimensions['min_width'] > width) ||
  344. (isset(dimensions, 'max_width') && dimensions['max_width'] < width) ||
  345. (isset(dimensions, 'height') && dimensions['height'] != height) ||
  346. (isset(dimensions, 'min_height') && dimensions['min_height'] > height) ||
  347. (isset(dimensions, 'max_height') && dimensions['max_height'] < height) ||
  348. (isset(dimensions, 'ratio') && dimensions['ratio'] != (width / height))
  349. ) {
  350. return false;
  351. }
  352. return true;
  353. }
  354. // 负责view的销毁
  355. function removeUploadFile(file) {
  356. var $li = getFileView(file.id);
  357. delete percentages[file.id];
  358. updateTotalProgress();
  359. $li.off().find('.file-panel').off().end().remove();
  360. }
  361. function updateTotalProgress() {
  362. var loaded = 0,
  363. total = 0,
  364. $bar = $progress.find('.progress-bar'),
  365. percent;
  366. $.each(percentages, function (k, v) {
  367. total += v[0];
  368. loaded += v[0] * v[1];
  369. });
  370. percent = total ? loaded / total : 0;
  371. percent = Math.round(percent * 100) + '%';
  372. $bar.text(percent);
  373. $bar.css('width', percent);
  374. updateStatusText();
  375. }
  376. function updateStatusText() {
  377. var text = '', stats;
  378. if (!uploader) {
  379. return;
  380. }
  381. if (state === 'ready') {
  382. stats = uploader.getStats();
  383. if (fileCount) {
  384. text = __('selected_files', {num: fileCount, size: WebUploader.formatSize(fileSize)});
  385. } else {
  386. showSuccess();
  387. }
  388. } else if (state === 'confirm') {
  389. stats = uploader.getStats();
  390. if (stats.uploadFailNum) {
  391. text = __('selected_has_failed', {success: stats.successNum, fail: stats.uploadFailNum});
  392. }
  393. } else {
  394. showSuccess();
  395. }
  396. function showSuccess() {
  397. stats = uploader.getStats();
  398. if (stats.successNum) {
  399. text = __('selected_success', {num: fileCount, size: WebUploader.formatSize(fileSize), success: stats.successNum});
  400. }
  401. if (stats.uploadFailNum) {
  402. text += (text ? __('dot') : '') + __('failed_num', {fail: stats.uploadFailNum});
  403. }
  404. }
  405. $info.html(text);
  406. }
  407. // 上传文件后修改字段值
  408. function updateFileColumn() {
  409. var values = getInput(),
  410. num = uploader.getStats().successNum,
  411. form = $.extend({}, opts.formData);
  412. if (!num || !values || !opts.autoUpdateColumn) {
  413. return;
  414. }
  415. if (relation) {
  416. if (!relation[1]) {
  417. // 新增子表记录,则不调用update接口
  418. return;
  419. }
  420. form[relation[0]] = {};
  421. form[relation[0]][relation[1]] = {};
  422. form[relation[0]][relation[1]][updateColumn] = values.join(',');
  423. } else {
  424. form[updateColumn] = values.join(',');
  425. }
  426. delete form['_relation'];
  427. delete form['upload_column'];
  428. $.post({
  429. url: opts.updateServer,
  430. data: form,
  431. });
  432. }
  433. function setState(val, args) {
  434. var stats;
  435. args = args || {};
  436. if (val === state) {
  437. return;
  438. }
  439. if ($upload) {
  440. $upload.removeClass('state-' + state);
  441. $upload.addClass('state-' + val);
  442. }
  443. state = val;
  444. switch (state) {
  445. case 'pedding':
  446. if (opts.disabled) return;
  447. $placeHolder.removeClass('element-invisible');
  448. $queue.hide();
  449. $statusBar.addClass('element-invisible');
  450. if (showImg) {
  451. $wrap.removeAttr('style');
  452. $wrap.find('.queueList').removeAttr('style');
  453. }
  454. refreshButton();
  455. break;
  456. case 'ready':
  457. $placeHolder.addClass('element-invisible');
  458. $selector.find(addFileButtonSelector).removeClass('element-invisible');
  459. $queue.show();
  460. if (!opts.disabled) {
  461. $statusBar.removeClass('element-invisible');
  462. }
  463. refreshButton();
  464. if (showImg) {
  465. $wrap.find('.queueList').css({'border': '1px solid #d3dde5', 'padding': '5px'});
  466. // $wrap.find('.queueList').removeAttr('style');
  467. }
  468. setTimeout(removeValidatorErrors, 1);
  469. break;
  470. case 'uploading':
  471. $selector.find(addFileButtonSelector).addClass('element-invisible');
  472. $progress.show();
  473. $upload.text(__('pause_upload'));
  474. break;
  475. case 'paused':
  476. $progress.show();
  477. $upload.text(__('go_on_upload'));
  478. break;
  479. case 'confirm':
  480. if (uploader) {
  481. $progress.hide();
  482. $selector.find(addFileButtonSelector).removeClass('element-invisible');
  483. $upload.text(__('start_upload'));
  484. stats = uploader.getStats();
  485. if (stats.successNum && !stats.uploadFailNum) {
  486. setState('finish');
  487. return;
  488. }
  489. }
  490. break;
  491. case 'finish':
  492. if (uploader) {
  493. stats = uploader.getStats();
  494. if (stats.successNum) {
  495. Dcat.success(__('upload_success_message', {success: stats.successNum}));
  496. setTimeout(function () {
  497. if (opts.upload.fileNumLimit == 1) {
  498. // 单文件上传,需要重置文件上传个数
  499. uploader.request('get-stats').numOfSuccess = 0;
  500. }
  501. }, 10);
  502. } else {
  503. // 没有成功的图片,重设
  504. state = 'done';
  505. location.reload();
  506. }
  507. }
  508. break;
  509. case 'decrOriginalFileNum':
  510. if (originalFilesNum > 0) originalFilesNum--;
  511. break;
  512. case 'incrOriginalFileNum':
  513. originalFilesNum++;
  514. break;
  515. case 'decrFileNumLimit': // 减少上传文件数量限制
  516. if (!uploader) {
  517. return;
  518. }
  519. var fileLimit = uploader.option('fileNumLimit'),
  520. num = args.num || 1;
  521. if (fileLimit == '-1') fileLimit = 0;
  522. num = fileLimit >= num ? fileLimit - num : 0;
  523. if (num == 0) num = '-1';
  524. uploader.option('fileNumLimit', num);
  525. break;
  526. case 'incrFileNumLimit': // 增加上传文件数量限制
  527. if (!uploader) {
  528. return;
  529. }
  530. var fileLimit = uploader.option('fileNumLimit'),
  531. num = args.num || 1;
  532. if (fileLimit == '-1') fileLimit = 0;
  533. num = fileLimit + num;
  534. uploader.option('fileNumLimit', num);
  535. break;
  536. case 'init': // 初始化
  537. $upload.addClass('state-' + state);
  538. updateTotalProgress();
  539. if (originalFilesNum || opts.disabled) {
  540. $placeHolder.addClass('element-invisible');
  541. if (!opts.disabled) {
  542. $statusBar.show();
  543. } else {
  544. $wrap.addClass('disabled');
  545. }
  546. setState('ready');
  547. } else if (showImg) {
  548. $wrap.removeAttr('style');
  549. $wrap.find('.queueList').css('margin', '0');
  550. }
  551. refreshButton();
  552. break;
  553. }
  554. updateStatusText();
  555. }
  556. // 移除form表单的文件
  557. function removeFormFile(fileId) {
  558. if (!fileId) return;
  559. var file = formFiles[fileId];
  560. deleteInput(fileId);
  561. delete formFiles[fileId];
  562. if (uploader && !file.fake) {
  563. uploader.removeFile(file);
  564. }
  565. setState('decrOriginalFileNum');
  566. setState('incrFileNumLimit');
  567. if (!Dcat.helpers.len(formFiles) && !Dcat.helpers.len(percentages)) {
  568. setState('pedding');
  569. }
  570. }
  571. // 获取表单值
  572. function getInput() {
  573. var val = $input.val();
  574. return val ? val.split(',') : [];
  575. }
  576. // 新增表单值
  577. function addInput(id) {
  578. var val = getInput();
  579. val.push(id);
  580. setInput(val);
  581. }
  582. // 设置表单值
  583. function setInput(arr) {
  584. arr = arr.filter(function (v, k, self) {
  585. return self.indexOf(v) === k;
  586. }).filter(function (v) {
  587. return v ? true : false;
  588. });
  589. $input.val(arr.join(','));
  590. }
  591. // 删除表单值
  592. function deleteInput(id) {
  593. deleteUploadedFile(id);
  594. if (!id) {
  595. return $input.val('');
  596. }
  597. setInput(getInput().filter(function (v) {
  598. return v != id;
  599. }));
  600. }
  601. // 添加已上传文件
  602. function appendUploadedFile(file) {
  603. if (!file.serverId || searchUploadedFile(file.serverId) !== -1) {
  604. return;
  605. }
  606. uploadedFiles.push(file)
  607. }
  608. function syncUploadedFiles() {
  609. var files = [];
  610. for (var i in uploadedFiles) {
  611. if (uploadedFiles[i]) {
  612. files.push(uploadedFiles[i].serverId);
  613. }
  614. }
  615. setInput(files);
  616. }
  617. function deleteUploadedFile(fileId) {
  618. uploadedFiles = uploadedFiles.filter(function (v) {
  619. return v.serverId != fileId;
  620. });
  621. }
  622. // 查找文件位置
  623. function searchUploadedFile(fileId) {
  624. for (var i in uploadedFiles) {
  625. if (uploadedFiles[i].serverId === fileId) {
  626. return i;
  627. }
  628. }
  629. return -1;
  630. }
  631. // 交换文件排序
  632. function swrapUploadedFile(fileId, order) {
  633. var index = parseInt(searchUploadedFile(fileId)),
  634. currentFile = uploadedFiles[index],
  635. prevFile = uploadedFiles[index - 1],
  636. nextFile = uploadedFiles[index + 1];
  637. if (order) {
  638. if (index === 0) {
  639. return;
  640. }
  641. uploadedFiles[index - 1] = currentFile;
  642. uploadedFiles[index] = prevFile;
  643. } else {
  644. if (!nextFile) {
  645. return;
  646. }
  647. uploadedFiles[index + 1] = currentFile;
  648. uploadedFiles[index] = nextFile;
  649. }
  650. syncUploadedFiles();
  651. }
  652. // 重新渲染已上传文件
  653. function rerenderUploadedFiles() {
  654. $queue.html('');
  655. for (var i in uploadedFiles) {
  656. if (uploadedFiles[i]) {
  657. appendUploadedFileForm(uploadedFiles[i])
  658. }
  659. }
  660. }
  661. // 重新计算按钮定位
  662. function refreshButton() {
  663. uploader.refresh();
  664. }
  665. function removeValidatorErrors() {
  666. $input.parents('.form-group,.form-label-group,.form-field').find('.with-errors').html('')
  667. }
  668. // 文件排序
  669. function orderFiles() {
  670. var $this = $(this),
  671. $li = $this.parents('li').first(),
  672. fileId = $this.data('id'),
  673. order = $this.data('order'),
  674. $prev = $li.prev(),
  675. $next = $li.next();
  676. if (order) {
  677. // 升序
  678. if (!$prev.length) {
  679. return;
  680. }
  681. swrapUploadedFile(fileId, order);
  682. rerenderUploadedFiles();
  683. return;
  684. }
  685. if (!$next.length) {
  686. return;
  687. }
  688. swrapUploadedFile(fileId, order);
  689. rerenderUploadedFiles();
  690. }
  691. // 添加上传成功文件到表单区域
  692. function appendUploadedFileForm(file) {
  693. var html = "";
  694. html += "<li title='" + file.serverPath + "'>";
  695. if (!showImg && opts.sortable) {
  696. // 文件排序
  697. html += `
  698. <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>
  699. <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>
  700. `;
  701. }
  702. if (showImg) {
  703. html += `<p class='imgWrap'><img src='${file.serverUrl}'></p>`
  704. } else if (!opts.disabled) {
  705. html += `<p class="file-action" data-file-act="delete" data-id="${file.serverId}"><i class="feather icon-trash red-dark"></i></p>`;
  706. }
  707. html += "<p class='title' style=''><i class='feather icon-check text-white icon-success text-white'></i>";
  708. html += file.serverPath;
  709. html += "</p>";
  710. if (showImg) {
  711. html += "<p class='title' style='margin-bottom:20px;'>&nbsp;</p>";
  712. html += "<div class='file-panel' >";
  713. if (!opts.disabled) {
  714. 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>`;
  715. }
  716. html += `<a class='btn btn-sm btn-white' data-file-act='preview' data-url='${file.serverUrl}' ><i class='feather icon-zoom-in'></i></a>`;
  717. if (opts.sortable) {
  718. // 文件排序
  719. html += `
  720. <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>
  721. <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>
  722. `;
  723. }
  724. html += "</div>";
  725. } else {
  726. }
  727. html += "</li>";
  728. html = $(html);
  729. if (!showImg) {
  730. html.find('.file-type').show();
  731. html.find('.title').show();
  732. $wrap.css('background', 'transparent');
  733. }
  734. var deleteFile = function () {
  735. var fileId = $(this).data('id'), post = opts.deleteData;
  736. if (opts.disableRemove) {
  737. html.remove();
  738. return removeFormFile(fileId);
  739. }
  740. Dcat.confirm(__('confirm_delete_file'), file.serverId, function () {
  741. post.key = fileId;
  742. post._column = updateColumn;
  743. post._relation = relation;
  744. Dcat.loading();
  745. $.post({
  746. url: opts.deleteUrl,
  747. data: post,
  748. success: function (result) {
  749. Dcat.loading(false);
  750. if (result.status) {
  751. // 移除
  752. html.remove();
  753. removeFormFile(fileId);
  754. return;
  755. }
  756. Dcat.error(result.message || 'Remove file failed.')
  757. }
  758. });
  759. });
  760. };
  761. // 删除按钮点击事件
  762. html.find('[data-file-act="deleteurl"]').click(deleteFile);
  763. html.find('[data-file-act="delete"]').click(deleteFile);
  764. // 文件排序
  765. if (opts.sortable) {
  766. html.find('[data-file-act="order"').click(orderFiles);
  767. }
  768. // 放大图片
  769. html.find('[data-file-act="preview"]').click(function () {
  770. var url = $(this).data('url');
  771. Dcat.helpers.previewImage(url);
  772. });
  773. formFiles[file.serverId] = file;
  774. addInput(file.serverId);
  775. $queue.append(html);
  776. if (showImg) {
  777. setTimeout(function () {
  778. html.css('margin', '5px');
  779. }, initImg ? 0 : 400);
  780. initImg = 1;
  781. }
  782. }
  783. // 初始化web-uploader
  784. function build() {
  785. $wrap = $selector.find(opts.wrapper);
  786. // 图片容器
  787. $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList'));
  788. // 状态栏,包括进度和控制按钮
  789. $statusBar = $wrap.find('.statusBar');
  790. // 文件总体选择信息。
  791. $info = $statusBar.find('.info');
  792. // 上传按钮
  793. $upload = $wrap.find('.upload-btn');
  794. // 没选择文件之前的内容。
  795. $placeHolder = $wrap.find('.placeholder');
  796. $progress = $statusBar.find('.upload-progress').hide();
  797. // IE;
  798. supportIe();
  799. // 实例化
  800. this.uploader = uploader = WebUploader.create(opts.upload);
  801. // 拖拽时不接受 js, txt 文件。
  802. uploader.on('dndAccept', function (items) {
  803. var denied = false,
  804. len = items.length,
  805. i = 0,
  806. // 修改js类型
  807. unAllowed = 'text/plain;application/javascript ';
  808. for (; i < len; i++) {
  809. // 如果在列表里面
  810. if (~unAllowed.indexOf(items[i].type)) {
  811. denied = true;
  812. break;
  813. }
  814. }
  815. return !denied;
  816. });
  817. if (opts.upload.fileNumLimit > 1 && !opts.disabled) {
  818. // 添加“添加文件”的按钮,
  819. uploader.addButton({
  820. id: addFileButtonSelector,
  821. label: '<i class="feather icon-folder"></i> &nbsp;' + __('go_on_add')
  822. });
  823. }
  824. uploader.onUploadProgress = function (file, percentage) {
  825. percentages[file.id][1] = percentage;
  826. updateTotalProgress();
  827. };
  828. uploader.onBeforeFileQueued = function (file) {
  829. };
  830. // 添加文件
  831. uploader.onFileQueued = function (file) {
  832. fileCount++;
  833. fileSize += file.size;
  834. if (fileCount === 1) {
  835. $placeHolder.addClass('element-invisible');
  836. $statusBar.show();
  837. }
  838. addFile(file);
  839. setState('ready');
  840. updateTotalProgress();
  841. if (!opts.disabled && opts.autoUpload) {
  842. // 自动上传
  843. uploader.upload()
  844. }
  845. };
  846. // 删除文件事件监听
  847. uploader.onFileDequeued = function (file) {
  848. fileCount--;
  849. fileSize -= file.size;
  850. if (!fileCount && !Dcat.helpers.len(formFiles)) {
  851. setState('pedding');
  852. }
  853. removeUploadFile(file);
  854. };
  855. uploader.on('all', function (type, obj, reason) {
  856. switch (type) {
  857. case 'uploadFinished':
  858. setState('confirm');
  859. updateFileColumn();
  860. break;
  861. case 'startUpload':
  862. setState('uploading');
  863. break;
  864. case 'stopUpload':
  865. setState('paused');
  866. break;
  867. case 'uploadAccept':
  868. // 上传失败,返回false
  869. //正常来说上传返回必须是个json 必须包含 reason.id 否则肯定出错了
  870. if (!reason || !reason.id) {
  871. var errorMessage;
  872. if (reason && reason.data && reason.data.message) {
  873. errorMessage = reason.data.message
  874. } else if(reason && reason.error) {
  875. errorMessage = reason.error.message //DCAT 原有的逻辑
  876. } else {
  877. errorMessage = "Unknown error!"
  878. }
  879. Dcat.error(errorMessage);
  880. faildFiles[obj.file.id] = obj.file;
  881. return false;
  882. }
  883. if (reason.merge) {
  884. // 分片上传
  885. return;
  886. }
  887. // 上传成功,保存新文件名和路径到file对象
  888. obj.file.serverId = reason.id;
  889. obj.file.serverName = reason.name;
  890. obj.file.serverPath = reason.path;
  891. obj.file.serverUrl = reason.url || null;
  892. appendUploadedFile(obj.file);
  893. addInput(reason.id);
  894. var $li = getFileView(obj.file.id);
  895. if (!showImg) {
  896. $li.find('.file-action').hide();
  897. $li.find('[data-file-act="delete"]').show();
  898. }
  899. if (opts.sortable) {
  900. $li.find('[data-file-act="order"]').removeClass('d-none').show();
  901. }
  902. break;
  903. }
  904. });
  905. uploader.onError = function (code) {
  906. switch (code) {
  907. case 'Q_TYPE_DENIED':
  908. Dcat.error(__('Q_TYPE_DENIED'));
  909. break;
  910. case 'Q_EXCEED_NUM_LIMIT':
  911. Dcat.error(__('Q_EXCEED_NUM_LIMIT', {num: opts.upload.fileNumLimit}));
  912. break;
  913. case 'F_EXCEED_SIZE':
  914. Dcat.error(__('F_EXCEED_SIZE'));
  915. break;
  916. case 'Q_EXCEED_SIZE_LIMIT':
  917. Dcat.error(__('Q_EXCEED_SIZE_LIMIT'));
  918. break;
  919. case 'F_DUPLICATE':
  920. Dcat.warning(__('F_DUPLICATE'));
  921. break;
  922. default:
  923. Dcat.error('Error: ' + code);
  924. }
  925. };
  926. $upload.on('click', function () {
  927. if ($(this).hasClass('disabled')) {
  928. return false;
  929. }
  930. if (state === 'ready') {
  931. uploader.upload();
  932. } else if (state === 'paused') {
  933. uploader.upload();
  934. } else if (state === 'uploading') {
  935. uploader.stop();
  936. }
  937. });
  938. $info.on('click', '.retry', function () {
  939. uploader.retry();
  940. });
  941. $info.on('click', '.ignore', function () {
  942. for (var i in faildFiles) {
  943. uploader.removeFile(i, true);
  944. delete faildFiles[i];
  945. }
  946. });
  947. setState('init');
  948. }
  949. // 预览
  950. function preview() {
  951. for (var i in opts.preview) {
  952. var path = opts.preview[i].path, ext;
  953. if (path.indexOf('.')) {
  954. ext = path.split('.').pop();
  955. }
  956. var file = {
  957. serverId: opts.preview[i].id,
  958. serverUrl: opts.preview[i].url,
  959. serverPath: path,
  960. ext: ext,
  961. fake: 1,
  962. };
  963. setState('incrOriginalFileNum');
  964. setState('decrFileNumLimit');
  965. appendUploadedFileForm(file);
  966. appendUploadedFile(file);
  967. }
  968. }
  969. this.uploader = uploader;
  970. this.options = opts;
  971. this.build = build;
  972. this.preview = preview;
  973. this.setState = setState;
  974. this.refreshButton = refreshButton;
  975. this.getFileView = getFileView;
  976. this.getFileViewSelector = getFileViewSelector;
  977. this.addFileView = addFile;
  978. this.removeUploadFileView = removeUploadFile;
  979. this.isImage = isImage;
  980. this.getColumn = function () {
  981. return updateColumn;
  982. };
  983. function supportIe() {
  984. if (!WebUploader.Uploader.support('flash') && WebUploader.browser.ie) {
  985. // flash 安装了但是版本过低。
  986. if (flashVersion) {
  987. (function (container) {
  988. window['expressinstallcallback'] = function (state) {
  989. switch (state) {
  990. case 'Download.Cancelled':
  991. break;
  992. case 'Download.Failed':
  993. Dcat.error('Install failed!');
  994. break;
  995. default:
  996. Dcat.success('Install Success!');
  997. break;
  998. }
  999. delete window['expressinstallcallback'];
  1000. };
  1001. var swf = './expressInstall.swf';
  1002. // insert flash object
  1003. var html = `<object type="application/x-shockwave-flash" data="${swf}" `;
  1004. if (WebUploader.browser.ie) {
  1005. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  1006. }
  1007. html += `width="100%" height="100%" style="outline:0">
  1008. <param name="movie" value="${swf}" />
  1009. <param name="wmode" value="transparent" />
  1010. <param name="allowscriptaccess" value="always" />
  1011. </object>`;
  1012. container.html(html);
  1013. })($wrap);
  1014. } else {
  1015. $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>');
  1016. }
  1017. return;
  1018. } else if (!WebUploader.Uploader.support()) {
  1019. Dcat.error('您的浏览器不支持Web Uploader!');
  1020. return;
  1021. }
  1022. }
  1023. return this;
  1024. }
  1025. Dcat.Uploader = function (options) {
  1026. return new Uploader(options)
  1027. };
  1028. })(window, jQuery);