upload.js 37 KB

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