upload.js 36 KB

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