upload.js 37 KB

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