upload.js 14 KB

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