upload.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. //提交文件
  171. $.ajax({
  172. url: options.url
  173. ,type: 'post'
  174. ,data: formData
  175. ,contentType: false
  176. ,processData: false
  177. ,dataType: 'json'
  178. ,headers: options.headers || {}
  179. ,success: function(res){
  180. successful++;
  181. done(index, res);
  182. allDone();
  183. }
  184. ,error: function(){
  185. aborted++;
  186. that.msg('请求上传接口出现异常');
  187. error(index);
  188. allDone();
  189. }
  190. });
  191. });
  192. }
  193. //低版本IE处理方式,不支持跨域
  194. ,iframeSend = function(){
  195. var iframe = $('#'+ ELEM_IFRAME);
  196. that.elemFile.parent().submit();
  197. //获取响应信息
  198. clearInterval(Class.timer);
  199. Class.timer = setInterval(function() {
  200. var res, iframeBody = iframe.contents().find('body');
  201. try {
  202. res = iframeBody.text();
  203. } catch(e) {
  204. that.msg('获取上传后的响应信息出现异常');
  205. clearInterval(Class.timer);
  206. error();
  207. }
  208. if(res){
  209. clearInterval(Class.timer);
  210. iframeBody.html('');
  211. done(0, res);
  212. }
  213. }, 30);
  214. }
  215. //统一回调
  216. ,done = function(index, res){
  217. that.elemFile.next('.'+ ELEM_CHOOSE).remove();
  218. elemFile.value = '';
  219. if(typeof res !== 'object'){
  220. try {
  221. res = JSON.parse(res);
  222. } catch(e){
  223. res = {};
  224. return that.msg('请对上传接口返回有效JSON');
  225. }
  226. }
  227. typeof options.done === 'function' && options.done(res, index || 0, function(files){
  228. that.upload(files);
  229. });
  230. }
  231. //统一网络异常回调
  232. ,error = function(index){
  233. if(options.auto){
  234. elemFile.value = '';
  235. }
  236. typeof options.error === 'function' && options.error(index || 0, function(files){
  237. that.upload(files);
  238. });
  239. }
  240. ,exts = options.exts
  241. ,check ,value = function(){
  242. var arr = [];
  243. layui.each(files || that.chooseFiles, function(i, item){
  244. arr.push(item.name);
  245. });
  246. return arr;
  247. }()
  248. //回调返回的参数
  249. ,args = {
  250. //预览
  251. preview: function(callback){
  252. that.preview(callback);
  253. }
  254. //上传
  255. ,upload: function(index, file){
  256. var thisFile = {};
  257. thisFile[index] = file;
  258. that.upload(thisFile);
  259. }
  260. //追加文件到队列
  261. ,pushFile: function(){
  262. that.files = that.files || {};
  263. layui.each(that.chooseFiles, function(index, item){
  264. that.files[index] = item;
  265. });
  266. return that.files;
  267. }
  268. //重置文件
  269. ,resetFile: function(index, file, filename){
  270. var newFile = new File([file], filename);
  271. that.files = that.files || {};
  272. that.files[index] = newFile;
  273. }
  274. }
  275. //提交上传
  276. ,send = function(){
  277. //选择文件的回调
  278. if(type === 'choose' || options.auto){
  279. options.choose && options.choose(args);
  280. if(type === 'choose'){
  281. return;
  282. }
  283. }
  284. //上传前的回调
  285. options.before && options.before(args);
  286. //IE兼容处理
  287. if(device.ie){
  288. return device.ie > 9 ? ajaxSend() : iframeSend();
  289. }
  290. ajaxSend();
  291. }
  292. //校验文件格式
  293. value = value.length === 0
  294. ? ((elemFile.value.match(/[^\/\\]+\..+/g)||[]) || '')
  295. : value;
  296. if(value.length === 0) return;
  297. switch(options.accept){
  298. case 'file': //一般文件
  299. if(exts && !RegExp('\\w\\.('+ exts +')$', 'i').test(escape(value))){
  300. that.msg('选择的文件中包含不支持的格式');
  301. return elemFile.value = '';
  302. }
  303. break;
  304. case 'video': //视频文件
  305. if(!RegExp('\\w\\.('+ (exts || 'avi|mp4|wma|rmvb|rm|flash|3gp|flv') +')$', 'i').test(escape(value))){
  306. that.msg('选择的视频中包含不支持的格式');
  307. return elemFile.value = '';
  308. }
  309. break;
  310. case 'audio': //音频文件
  311. if(!RegExp('\\w\\.('+ (exts || 'mp3|wav|mid') +')$', 'i').test(escape(value))){
  312. that.msg('选择的音频中包含不支持的格式');
  313. return elemFile.value = '';
  314. }
  315. break;
  316. default: //图片文件
  317. layui.each(value, function(i, item){
  318. if(!RegExp('\\w\\.('+ (exts || 'jpg|png|gif|bmp|jpeg$') +')', 'i').test(escape(item))){
  319. check = true;
  320. }
  321. });
  322. if(check){
  323. that.msg('选择的图片中包含不支持的格式');
  324. return elemFile.value = '';
  325. }
  326. break;
  327. }
  328. //检验文件数量
  329. that.fileLength = function(){
  330. var length = 0
  331. ,items = files || that.files || that.chooseFiles || elemFile.files;
  332. layui.each(items, function(){
  333. length++;
  334. });
  335. return length;
  336. }();
  337. if(options.number && that.fileLength > options.number){
  338. return that.msg('同时最多只能上传的数量为:'+ options.number);
  339. }
  340. //检验文件大小
  341. if(options.size > 0 && !(device.ie && device.ie < 10)){
  342. var limitSize;
  343. layui.each(that.chooseFiles, function(index, file){
  344. if(file.size > 1024*options.size){
  345. var size = options.size/1024;
  346. size = size >= 1 ? (size.toFixed(2) + 'MB') : options.size + 'KB'
  347. elemFile.value = '';
  348. limitSize = size;
  349. }
  350. });
  351. if(limitSize) return that.msg('文件不能超过'+ limitSize);
  352. }
  353. send();
  354. };
  355. //事件处理
  356. Class.prototype.events = function(){
  357. var that = this
  358. ,options = that.config
  359. //设置当前选择的文件队列
  360. ,setChooseFile = function(files){
  361. that.chooseFiles = {};
  362. layui.each(files, function(i, item){
  363. var time = new Date().getTime();
  364. that.chooseFiles[time + '-' + i] = item;
  365. });
  366. }
  367. //设置选择的文本
  368. ,setChooseText = function(files, filename){
  369. var elemFile = that.elemFile
  370. ,value = files.length > 1
  371. ? files.length + '个文件'
  372. : ((files[0] || {}).name || (elemFile[0].value.match(/[^\/\\]+\..+/g)||[]) || '');
  373. if(elemFile.next().hasClass(ELEM_CHOOSE)){
  374. elemFile.next().remove();
  375. }
  376. that.upload(null, 'choose');
  377. if(that.isFile() || options.choose) return;
  378. elemFile.after('<span class="layui-inline '+ ELEM_CHOOSE +'">'+ value +'</span>');
  379. };
  380. //点击上传容器
  381. options.elem.off('upload.start').on('upload.start', function(){
  382. var othis = $(this), data = othis.attr('lay-data');
  383. if(data){
  384. try{
  385. data = new Function('return '+ data)();
  386. that.config = $.extend({}, options, data);
  387. } catch(e){
  388. hint.error('Upload element property lay-data configuration item has a syntax error: ' + data)
  389. }
  390. }
  391. that.config.item = othis;
  392. that.elemFile[0].click();
  393. });
  394. //拖拽上传
  395. if(!(device.ie && device.ie < 10)){
  396. options.elem.off('upload.over').on('upload.over', function(){
  397. var othis = $(this)
  398. othis.attr('lay-over', '');
  399. })
  400. .off('upload.leave').on('upload.leave', function(){
  401. var othis = $(this)
  402. othis.removeAttr('lay-over');
  403. })
  404. .off('upload.drop').on('upload.drop', function(e, param){
  405. var othis = $(this), files = param.originalEvent.dataTransfer.files || [];
  406. othis.removeAttr('lay-over');
  407. setChooseFile(files);
  408. if(options.auto){
  409. that.upload(files);
  410. } else {
  411. setChooseText(files);
  412. }
  413. });
  414. }
  415. //文件选择
  416. that.elemFile.off('upload.change').on('upload.change', function(){
  417. var files = this.files || [];
  418. setChooseFile(files);
  419. options.auto ? that.upload() : setChooseText(files); //是否自动触发上传
  420. });
  421. //手动触发上传
  422. options.bindAction.off('upload.action').on('upload.action', function(){
  423. that.upload();
  424. });
  425. //防止事件重复绑定
  426. if(options.elem.data('haveEvents')) return;
  427. that.elemFile.on('change', function(){
  428. $(this).trigger('upload.change');
  429. });
  430. options.elem.on('click', function(){
  431. if(that.isFile()) return;
  432. $(this).trigger('upload.start');
  433. });
  434. if(options.drag){
  435. options.elem.on('dragover', function(e){
  436. e.preventDefault();
  437. $(this).trigger('upload.over');
  438. }).on('dragleave', function(e){
  439. $(this).trigger('upload.leave');
  440. }).on('drop', function(e){
  441. e.preventDefault();
  442. $(this).trigger('upload.drop', e);
  443. });
  444. }
  445. options.bindAction.on('click', function(){
  446. $(this).trigger('upload.action');
  447. });
  448. options.elem.data('haveEvents', true);
  449. };
  450. //核心入口
  451. upload.render = function(options){
  452. var inst = new Class(options);
  453. return thisUpload.call(inst);
  454. };
  455. exports(MOD_NAME, upload);
  456. });