upload.js 37 KB

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