upload.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /**
  2. @Title: layui.upload 文件上传
  3. @Author: 贤心
  4. @License:MIT
  5. */
  6. layui.define('layer' , function(exports){
  7. "use strict";
  8. var $ = layui.$
  9. ,layer = layui.layer
  10. ,hint = layui.hint()
  11. ,device = layui.device()
  12. //外部接口
  13. ,upload = {
  14. config: {} //全局配置项
  15. //设置全局项
  16. ,set: function(options){
  17. var that = this;
  18. that.config = $.extend({}, that.config, options);
  19. return that;
  20. }
  21. //事件监听
  22. ,on: function(events, callback){
  23. return layui.onevent.call(this, MOD_NAME, events, callback);
  24. }
  25. }
  26. //操作当前实例
  27. ,thisUpload = function(){
  28. var that = this;
  29. return {
  30. upload: function(files){
  31. that.upload.call(that, files);
  32. }
  33. ,config: that.config
  34. }
  35. }
  36. //字符常量
  37. ,MOD_NAME = 'upload', ELEM = '.layui-upload', THIS = 'layui-this', SHOW = 'layui-show', HIDE = 'layui-hide', DISABLED = 'layui-disabled'
  38. ,ELEM_FILE = 'layui-upload-file', ELEM_FORM = 'layui-upload-form', ELEM_IFRAME = 'layui-upload-iframe', ELEM_CHOOSE = 'layui-upload-choose', ELEM_DRAG = 'layui-upload-drag'
  39. //构造器
  40. ,Class = function(options){
  41. var that = this;
  42. that.config = $.extend({}, that.config, upload.config, options);
  43. that.render();
  44. };
  45. //默认配置
  46. Class.prototype.config = {
  47. accept: 'images' //允许上传的文件类型:images/file/video/audio
  48. ,exts: '' //允许上传的文件后缀名
  49. ,auto: true //是否选完文件后自动上传
  50. ,bindAction: '' //手动上传触发的元素
  51. ,url: '' //上传地址
  52. ,field: 'file' //文件字段名
  53. ,method: 'post' //请求上传的 http 类型
  54. ,data: {} //请求上传的额外参数
  55. ,drag: true //是否允许拖拽上传
  56. ,size: 0 //文件限制大小,默认不限制
  57. ,number: 0 //允许同时上传的文件数,默认不限制
  58. ,multiple: false //是否允许多文件上传,不支持ie8-9
  59. };
  60. //初始渲染
  61. Class.prototype.render = function(options){
  62. var that = this
  63. ,options = that.config;
  64. options.elem = $(options.elem);
  65. options.bindAction = $(options.bindAction);
  66. that.file();
  67. that.events();
  68. };
  69. //追加文件域
  70. Class.prototype.file = function(){
  71. var that = this
  72. ,options = that.config
  73. ,elemFile = that.elemFile = $([
  74. '<input class="'+ ELEM_FILE +'" type="file" accept="'+ options.acceptMime +'" name="'+ options.field +'"'
  75. ,(options.multiple ? ' multiple' : '')
  76. ,'>'
  77. ].join(''))
  78. ,next = options.elem.next();
  79. if(next.hasClass(ELEM_FILE) || next.hasClass(ELEM_FORM)){
  80. next.remove();
  81. }
  82. //包裹ie8/9容器
  83. if(device.ie && device.ie < 10){
  84. options.elem.wrap('<div class="layui-upload-wrap"></div>');
  85. }
  86. that.isFile() ? (
  87. that.elemFile = options.elem
  88. ,options.field = options.elem[0].name
  89. ) : options.elem.after(elemFile);
  90. //初始化ie8/9的Form域
  91. if(device.ie && device.ie < 10){
  92. that.initIE();
  93. }
  94. };
  95. //ie8-9初始化
  96. Class.prototype.initIE = function(){
  97. var that = this
  98. ,options = that.config
  99. ,iframe = $('<iframe id="'+ ELEM_IFRAME +'" class="'+ ELEM_IFRAME +'" name="'+ ELEM_IFRAME +'" frameborder="0"></iframe>')
  100. ,elemForm = $(['<form target="'+ ELEM_IFRAME +'" class="'+ ELEM_FORM +'" method="post" key="set-mine" enctype="multipart/form-data" action="'+ options.url +'">'
  101. ,'</form>'].join(''));
  102. //插入iframe
  103. $('#'+ ELEM_IFRAME)[0] || $('body').append(iframe);
  104. //包裹文件域
  105. if(!options.elem.next().hasClass(ELEM_FORM)){
  106. that.elemFile.wrap(elemForm);
  107. //追加额外的参数
  108. options.elem.next('.'+ ELEM_FORM).append(function(){
  109. var arr = [];
  110. layui.each(options.data, function(key, value){
  111. value = typeof value === 'function' ? value() : value;
  112. arr.push('<input type="hidden" name="'+ key +'" value="'+ value +'">')
  113. });
  114. return arr.join('');
  115. }());
  116. }
  117. };
  118. //异常提示
  119. Class.prototype.msg = function(content){
  120. return layer.msg(content, {
  121. icon: 2
  122. ,shift: 6
  123. });
  124. };
  125. //判断绑定元素是否为文件域本身
  126. Class.prototype.isFile = function(){
  127. var elem = this.config.elem[0];
  128. if(!elem) return;
  129. return elem.tagName.toLocaleLowerCase() === 'input' && elem.type === 'file'
  130. }
  131. //预读图片信息
  132. Class.prototype.preview = function(callback){
  133. var that = this;
  134. if(window.FileReader){
  135. layui.each(that.chooseFiles, function(index, file){
  136. var reader = new FileReader();
  137. reader.readAsDataURL(file);
  138. reader.onload = function(){
  139. callback && callback(index, file, this.result);
  140. }
  141. });
  142. }
  143. };
  144. //执行上传
  145. Class.prototype.upload = function(files, type){
  146. var that = this
  147. ,options = that.config
  148. ,elemFile = that.elemFile[0]
  149. //高级浏览器处理方式,支持跨域
  150. ,ajaxSend = function(){
  151. var successful = 0, aborted = 0
  152. ,items = files || that.files || that.chooseFiles || elemFile.files
  153. ,allDone = function(){ //多文件全部上传完毕的回调
  154. if(options.multiple && successful + aborted === that.fileLength){
  155. typeof options.allDone === 'function' && options.allDone({
  156. total: that.fileLength
  157. ,successful: successful
  158. ,aborted: aborted
  159. });
  160. }
  161. };
  162. layui.each(items, function(index, file){
  163. var formData = new FormData();
  164. formData.append(options.field, file);
  165. //追加额外的参数
  166. layui.each(options.data, function(key, value){
  167. value = typeof value === 'function' ? value() : value;
  168. formData.append(key, value);
  169. });
  170. if (file.key) {
  171. formData.append('key', file.key);
  172. }
  173. //提交文件
  174. $.ajax({
  175. url: options.url
  176. ,type: 'post'
  177. ,data: formData
  178. ,contentType: false
  179. ,processData: false
  180. ,dataType: 'json'
  181. ,headers: options.headers || {}
  182. ,success: function(res){
  183. successful++;
  184. done(index, res, file);
  185. allDone();
  186. }
  187. ,xhr:options.xhr(function(e){//此处为新添加功能
  188. var percent=Math.floor((e.loaded / e.total)*100);//计算百分比
  189. options.progress(percent);//回调将数值返回
  190. })
  191. ,error: function(){
  192. aborted++;
  193. that.msg('请求上传接口出现异常');
  194. error(index);
  195. allDone();
  196. }
  197. });
  198. });
  199. }
  200. //低版本IE处理方式,不支持跨域
  201. ,iframeSend = function(){
  202. var iframe = $('#'+ ELEM_IFRAME);
  203. that.elemFile.parent().submit();
  204. //获取响应信息
  205. clearInterval(Class.timer);
  206. Class.timer = setInterval(function() {
  207. var res, iframeBody = iframe.contents().find('body');
  208. try {
  209. res = iframeBody.text();
  210. } catch(e) {
  211. that.msg('获取上传后的响应信息出现异常');
  212. clearInterval(Class.timer);
  213. error();
  214. }
  215. if(res){
  216. clearInterval(Class.timer);
  217. iframeBody.html('');
  218. done(0, res);
  219. }
  220. }, 30);
  221. }
  222. //统一回调
  223. ,done = function(index, res, file){
  224. that.elemFile.next('.'+ ELEM_CHOOSE).remove();
  225. elemFile.value = '';
  226. if(typeof res !== 'object'){
  227. try {
  228. res = JSON.parse(res);
  229. } catch(e){
  230. res = {};
  231. return that.msg('请对上传接口返回有效JSON');
  232. }
  233. }
  234. typeof options.done === 'function' && options.done(res, file, index || 0, function(files){
  235. that.upload(files);
  236. });
  237. }
  238. //统一网络异常回调
  239. ,error = function(index){
  240. if(options.auto){
  241. elemFile.value = '';
  242. }
  243. typeof options.error === 'function' && options.error(index || 0, function(files){
  244. that.upload(files);
  245. });
  246. }
  247. ,exts = options.exts
  248. ,check ,value = function(){
  249. var arr = [];
  250. layui.each(files || that.chooseFiles, function(i, item){
  251. arr.push(item.name);
  252. });
  253. return arr;
  254. }()
  255. //回调返回的参数
  256. ,args = {
  257. //预览
  258. preview: function(callback){
  259. that.preview(callback);
  260. }
  261. //上传
  262. ,upload: function(index, file){
  263. var thisFile = {};
  264. thisFile[index] = file;
  265. that.upload(thisFile);
  266. }
  267. //追加文件到队列
  268. ,pushFile: function(){
  269. that.files = that.files || {};
  270. layui.each(that.chooseFiles, function(index, item){
  271. that.files[index] = item;
  272. });
  273. return that.files;
  274. }
  275. //重置文件
  276. ,resetFile: function(index, file, filename){
  277. var newFile = new File([file], filename);
  278. that.files = that.files || {};
  279. that.files[index] = newFile;
  280. }
  281. //编辑文件
  282. ,editFile: function(path, cover){
  283. layui.each(that.chooseFiles, function(index, item){
  284. var temp = item.name.split('.');
  285. if (cover == 1) {
  286. that.chooseFiles[index]['key'] = path + hex_md5(item.name) + '.' + temp[temp.length-1];
  287. } else {
  288. var timestamp = Date.parse(new Date());
  289. that.chooseFiles[index]['key'] = path + hex_md5(item.name + '_' + timestamp) + '.' + temp[temp.length-1];
  290. }
  291. });
  292. return that.files;
  293. }
  294. }
  295. //提交上传
  296. ,send = function(){
  297. //选择文件的回调
  298. if(type === 'choose' || options.auto){
  299. options.choose && options.choose(args);
  300. if(type === 'choose'){
  301. return;
  302. }
  303. }
  304. //上传前的回调
  305. options.before && options.before(args);
  306. //IE兼容处理
  307. if(device.ie){
  308. return device.ie > 9 ? ajaxSend() : iframeSend();
  309. }
  310. ajaxSend();
  311. }
  312. //校验文件格式
  313. value = value.length === 0
  314. ? ((elemFile.value.match(/[^\/\\]+\..+/g)||[]) || '')
  315. : value;
  316. if(value.length === 0) return;
  317. switch(options.accept){
  318. case 'file': //一般文件
  319. if(exts && !RegExp('\\w\\.('+ exts +')$', 'i').test(escape(value))){
  320. that.msg('选择的文件中包含不支持的格式');
  321. return elemFile.value = '';
  322. }
  323. break;
  324. case 'video': //视频文件
  325. if(!RegExp('\\w\\.('+ (exts || 'avi|mp4|wma|rmvb|rm|flash|3gp|flv') +')$', 'i').test(escape(value))){
  326. that.msg('选择的视频中包含不支持的格式');
  327. return elemFile.value = '';
  328. }
  329. break;
  330. case 'audio': //音频文件
  331. if(!RegExp('\\w\\.('+ (exts || 'mp3|wav|mid') +')$', 'i').test(escape(value))){
  332. that.msg('选择的音频中包含不支持的格式');
  333. return elemFile.value = '';
  334. }
  335. break;
  336. default: //图片文件
  337. layui.each(value, function(i, item){
  338. if(!RegExp('\\w\\.('+ (exts || 'jpg|png|gif|bmp|jpeg$') +')', 'i').test(escape(item))){
  339. check = true;
  340. }
  341. });
  342. if(check){
  343. that.msg('选择的图片中包含不支持的格式');
  344. return elemFile.value = '';
  345. }
  346. break;
  347. }
  348. //检验文件数量
  349. that.fileLength = function(){
  350. var length = 0
  351. ,items = files || that.files || that.chooseFiles || elemFile.files;
  352. layui.each(items, function(){
  353. length++;
  354. });
  355. return length;
  356. }();
  357. if(options.number && that.fileLength > options.number){
  358. return that.msg('同时最多只能上传的数量为:'+ options.number);
  359. }
  360. //检验文件大小
  361. if(options.size > 0 && !(device.ie && device.ie < 10)){
  362. var limitSize;
  363. layui.each(that.chooseFiles, function(index, file){
  364. if(file.size > 1024*options.size){
  365. var size = options.size/1024;
  366. size = size >= 1 ? (size.toFixed(2) + 'MB') : options.size + 'KB'
  367. elemFile.value = '';
  368. limitSize = size;
  369. }
  370. });
  371. if(limitSize) return that.msg('文件不能超过'+ limitSize);
  372. }
  373. send();
  374. };
  375. //事件处理
  376. Class.prototype.events = function(){
  377. var that = this
  378. ,options = that.config
  379. //设置当前选择的文件队列
  380. ,setChooseFile = function(files){
  381. that.chooseFiles = {};
  382. layui.each(files, function(i, item){
  383. var time = new Date().getTime();
  384. that.chooseFiles[time + '-' + i] = item;
  385. });
  386. }
  387. //设置选择的文本
  388. ,setChooseText = function(files, filename){
  389. var elemFile = that.elemFile
  390. ,value = files.length > 1
  391. ? files.length + '个文件'
  392. : ((files[0] || {}).name || (elemFile[0].value.match(/[^\/\\]+\..+/g)||[]) || '');
  393. if(elemFile.next().hasClass(ELEM_CHOOSE)){
  394. elemFile.next().remove();
  395. }
  396. that.upload(null, 'choose');
  397. if(that.isFile() || options.choose) return;
  398. elemFile.after('<span class="layui-inline '+ ELEM_CHOOSE +'">'+ value +'</span>');
  399. };
  400. //点击上传容器
  401. options.elem.off('upload.start').on('upload.start', function(){
  402. var othis = $(this), data = othis.attr('lay-data');
  403. if(data){
  404. try{
  405. data = new Function('return '+ data)();
  406. that.config = $.extend({}, options, data);
  407. } catch(e){
  408. hint.error('Upload element property lay-data configuration item has a syntax error: ' + data)
  409. }
  410. }
  411. that.config.item = othis;
  412. that.elemFile[0].click();
  413. });
  414. //拖拽上传
  415. if(!(device.ie && device.ie < 10)){
  416. options.elem.off('upload.over').on('upload.over', function(){
  417. var othis = $(this)
  418. othis.attr('lay-over', '');
  419. })
  420. .off('upload.leave').on('upload.leave', function(){
  421. var othis = $(this)
  422. othis.removeAttr('lay-over');
  423. })
  424. .off('upload.drop').on('upload.drop', function(e, param){
  425. var othis = $(this), files = param.originalEvent.dataTransfer.files || [];
  426. othis.removeAttr('lay-over');
  427. setChooseFile(files);
  428. if(options.auto){
  429. that.upload(files);
  430. } else {
  431. setChooseText(files);
  432. }
  433. });
  434. }
  435. //文件选择
  436. that.elemFile.off('upload.change').on('upload.change', function(){
  437. var files = this.files || [];
  438. setChooseFile(files);
  439. options.auto ? that.upload() : setChooseText(files); //是否自动触发上传
  440. });
  441. //手动触发上传
  442. options.bindAction.off('upload.action').on('upload.action', function(){
  443. that.upload();
  444. });
  445. //防止事件重复绑定
  446. if(options.elem.data('haveEvents')) return;
  447. that.elemFile.on('change', function(){
  448. $(this).trigger('upload.change');
  449. });
  450. options.elem.on('click', function(){
  451. if(that.isFile()) return;
  452. $(this).trigger('upload.start');
  453. });
  454. if(options.drag){
  455. options.elem.on('dragover', function(e){
  456. e.preventDefault();
  457. $(this).trigger('upload.over');
  458. }).on('dragleave', function(e){
  459. $(this).trigger('upload.leave');
  460. }).on('drop', function(e){
  461. e.preventDefault();
  462. $(this).trigger('upload.drop', e);
  463. });
  464. }
  465. options.bindAction.on('click', function(){
  466. $(this).trigger('upload.action');
  467. });
  468. options.elem.data('haveEvents', true);
  469. };
  470. //核心入口
  471. upload.render = function(options){
  472. var inst = new Class(options);
  473. return thisUpload.call(inst);
  474. };
  475. exports(MOD_NAME, upload);
  476. });