upload.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  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. if (reason && reason.error) {
  870. Dcat.error(reason.error.message);
  871. faildFiles[obj.file.id] = obj.file;
  872. return false;
  873. }
  874. if (reason.merge) {
  875. // 分片上传
  876. return;
  877. }
  878. // 上传成功,保存新文件名和路径到file对象
  879. obj.file.serverId = reason.id;
  880. obj.file.serverName = reason.name;
  881. obj.file.serverPath = reason.path;
  882. obj.file.serverUrl = reason.url || null;
  883. appendUploadedFile(obj.file);
  884. addInput(reason.id);
  885. var $li = getFileView(obj.file.id);
  886. if (!showImg) {
  887. $li.find('.file-action').hide();
  888. $li.find('[data-file-act="delete"]').show();
  889. }
  890. if (opts.sortable) {
  891. $li.find('[data-file-act="order"]').removeClass('d-none').show();
  892. }
  893. break;
  894. }
  895. });
  896. uploader.onError = function (code) {
  897. switch (code) {
  898. case 'Q_TYPE_DENIED':
  899. Dcat.error(__('Q_TYPE_DENIED'));
  900. break;
  901. case 'Q_EXCEED_NUM_LIMIT':
  902. Dcat.error(__('Q_EXCEED_NUM_LIMIT', {num: opts.upload.fileNumLimit}));
  903. break;
  904. case 'F_EXCEED_SIZE':
  905. Dcat.error(__('F_EXCEED_SIZE'));
  906. break;
  907. case 'Q_EXCEED_SIZE_LIMIT':
  908. Dcat.error(__('Q_EXCEED_SIZE_LIMIT'));
  909. break;
  910. case 'F_DUPLICATE':
  911. Dcat.warning(__('F_DUPLICATE'));
  912. break;
  913. default:
  914. Dcat.error('Error: ' + code);
  915. }
  916. };
  917. $upload.on('click', function () {
  918. if ($(this).hasClass('disabled')) {
  919. return false;
  920. }
  921. if (state === 'ready') {
  922. uploader.upload();
  923. } else if (state === 'paused') {
  924. uploader.upload();
  925. } else if (state === 'uploading') {
  926. uploader.stop();
  927. }
  928. });
  929. $info.on('click', '.retry', function () {
  930. uploader.retry();
  931. });
  932. $info.on('click', '.ignore', function () {
  933. for (var i in faildFiles) {
  934. uploader.removeFile(i, true);
  935. delete faildFiles[i];
  936. }
  937. });
  938. setState('init');
  939. }
  940. // 预览
  941. function preview() {
  942. for (var i in opts.preview) {
  943. var path = opts.preview[i].path, ext;
  944. if (path.indexOf('.')) {
  945. ext = path.split('.').pop();
  946. }
  947. var file = {
  948. serverId: opts.preview[i].id,
  949. serverUrl: opts.preview[i].url,
  950. serverPath: path,
  951. ext: ext,
  952. fake: 1,
  953. };
  954. setState('incrOriginalFileNum');
  955. setState('decrFileNumLimit');
  956. appendUploadedFileForm(file);
  957. appendUploadedFile(file);
  958. }
  959. }
  960. this.uploader = uploader;
  961. this.options = opts;
  962. this.build = build;
  963. this.preview = preview;
  964. this.setState = setState;
  965. this.refreshButton = refreshButton;
  966. this.getFileView = getFileView;
  967. this.getFileViewSelector = getFileViewSelector;
  968. this.addFileView = addFile;
  969. this.removeUploadFileView = removeUploadFile;
  970. this.isImage = isImage;
  971. this.getColumn = function () {
  972. return updateColumn;
  973. };
  974. function supportIe() {
  975. if (!WebUploader.Uploader.support('flash') && WebUploader.browser.ie) {
  976. // flash 安装了但是版本过低。
  977. if (flashVersion) {
  978. (function (container) {
  979. window['expressinstallcallback'] = function (state) {
  980. switch (state) {
  981. case 'Download.Cancelled':
  982. break;
  983. case 'Download.Failed':
  984. Dcat.error('Install failed!');
  985. break;
  986. default:
  987. Dcat.success('Install Success!');
  988. break;
  989. }
  990. delete window['expressinstallcallback'];
  991. };
  992. var swf = './expressInstall.swf';
  993. // insert flash object
  994. var html = `<object type="application/x-shockwave-flash" data="${swf}" `;
  995. if (WebUploader.browser.ie) {
  996. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  997. }
  998. html += `width="100%" height="100%" style="outline:0">
  999. <param name="movie" value="${swf}" />
  1000. <param name="wmode" value="transparent" />
  1001. <param name="allowscriptaccess" value="always" />
  1002. </object>`;
  1003. container.html(html);
  1004. })($wrap);
  1005. } else {
  1006. $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>');
  1007. }
  1008. return;
  1009. } else if (!WebUploader.Uploader.support()) {
  1010. Dcat.error('您的浏览器不支持Web Uploader!');
  1011. return;
  1012. }
  1013. }
  1014. return this;
  1015. }
  1016. Dcat.Uploader = function (options) {
  1017. return new Uploader(options)
  1018. };
  1019. })(window, jQuery);