upload.js 15 KB

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