upload.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. var fileReader = new FileReader();
  2. fileReader.onload = function(ev) {
  3. try {
  4. var data = ev.target.result
  5. var workbook = XLSX.read(data, {
  6. type: 'binary'
  7. }) // 以二进制流方式读取得到整份excel表格对象
  8. var persons = []; // 存储获取到的数据
  9. } catch (e) {
  10. console.log('文件类型不正确');
  11. return;
  12. }
  13. // 表格的表格范围,可用于判断表头是否数量是否正确
  14. var fromTo = '';
  15. // 遍历每张表读取
  16. for (var sheet in workbook.Sheets) {
  17. if (workbook.Sheets.hasOwnProperty(sheet)) {
  18. fromTo = workbook.Sheets[sheet]['!ref'];
  19. console.log(fromTo);
  20. persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
  21. // break; // 如果只取第一张表,就取消注释这行
  22. }
  23. }
  24. //在控制台打印出来表格中的数据
  25. console.log(persons);
  26. var tableHtml = '<table class="exceltable"><thead id="tablehead" class="tablehead"></thead><tbody id="tablebody" class="tablebody"></tbody></table>';
  27. var tableWith=window.innerWidth-100;
  28. layer.open({
  29. title: '数据文件预览',
  30. type: '1',
  31. closeBtn: false,
  32. area: [tableWith+'px', '600px'],
  33. content: '<div><div class="box-contact-info">' + tableHtml + '</div></div>',
  34. success: function (obj, layerIndex) {
  35. for(var j=0;j<persons.length;j++){
  36. var arr=persons[j];
  37. if(j==0){
  38. $("#tablehead").append("<tr class='exceltitle'></tr>");
  39. }
  40. $("#tablebody").append("<tr class='excelcontent'></tr>");
  41. for (var i in arr) {
  42. //alert(i+"---"+arr[i]);
  43. if(j==0){
  44. $(".exceltitle").append("<th>"+i+"</th>");
  45. }
  46. $(".excelcontent").eq(j).append("<td>"+arr[i]+"</td>");
  47. }
  48. if(j>20){
  49. break;
  50. }
  51. }
  52. $('.upload-close-btn').on('click',function(){
  53. layer.confirm('您确定要取消上传吗?', {icon: 3, title:'提示'}, function(index){
  54. layer.closeAll();
  55. });
  56. });
  57. }
  58. });
  59. };
  60. function uploadShow(options) {
  61. var settings = {
  62. sessionId: '0',
  63. url:'',
  64. choose:function(obj){
  65. console.log('选择完成');
  66. console.log(obj);
  67. },
  68. before:function(obj){
  69. console.log('上传前');
  70. console.log(obj);
  71. },
  72. done: function(res, index, upload){
  73. console.log('上传成功');
  74. console.log(res);
  75. },
  76. allDone: function(obj){
  77. console.log('多文件上传回调');
  78. console.log(obj);
  79. },
  80. error: function (index, upload) {
  81. console.log('上传失败');
  82. console.log(index);
  83. },
  84. progress: function(n, elem){
  85. console.log('上传进度');
  86. var percent = n + '%'
  87. }
  88. };
  89. ops = $.extend({}, settings, options);
  90. var contentHtml = '<div class="upload-file-tips">注意:您可以上传大小10M以内的文件。</div>\
  91. <div class="upload-file-title"><span id="selectfiles'+ ops.sessionId + '" class="upload-select-btn">+添加文件</span>请选择<strong>xls,xlsx</strong>格式的文件上传</div>\
  92. <div class="upload-file-box"><table id="readyfile'+ ops.sessionId + '" class="upload-file-table" width="100%" cellpadding="0" cellspacing="0"><tr><th width="40%">文件名称</th><th width="10%">进度</th><th width="15%">状态</th><th width="15%">大小</th><th width="20%">操作</th></tr><tr class="upload-file-none"><td colspan="5" style="color:#999;">请点击【添加文件】按钮,选择需要上传的文件</td></tr></table></div>\
  93. <div class="upload-file-bottom"><span id="postfiles'+ ops.sessionId + '" class="upload-post-btn">开始上传</span><span class="upload-close-btn">取消</span></div>';
  94. layer.open({
  95. title: '上传数据文件',
  96. type: '1',
  97. closeBtn: false,
  98. area: ['800px', 'auto'],
  99. content: '<div><div class="box-contact-info">' + contentHtml + '</div></div>',
  100. success: function (obj, layerIndex) {
  101. var boxh = $('#layui-layer' + layerIndex).height();
  102. var boxt = $('#layui-layer' + layerIndex).offset().top;
  103. var bodyh = window.innerHeight;
  104. //重新给指定层设定width、top等
  105. var demoListView=$('#readyfile'+ops.sessionId),
  106. uploadListIns = upload.render({
  107. elem: '#selectfiles'+ops.sessionId
  108. , url: ops.url
  109. , accept: 'file'
  110. , acceptMime:'.xls,.xlsx'
  111. , exts:'xls|xlsx'
  112. , multiple: true
  113. , auto: false
  114. , size: 10*1024
  115. , bindAction: '#postfiles'+ops.sessionId
  116. , data: { use: 'file', action: 'project' }
  117. , choose: function (obj) {
  118. var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
  119. //读取本地文件
  120. obj.preview(function (index, file, result) {
  121. var tr = $(['<tr id="upload-' + index + '">'
  122. , '<td style="text-align:left;">' + file.name + '</td>'
  123. , '<td><div class="file-progress" id="progress_' + index + '">0%</div></td>'
  124. , '<td align="center">等待上传</td>'
  125. , '<td align="center">' + (file.size / (1024 * 1024)).toFixed(1) + 'MB</td>'
  126. , '<td align="center">'
  127. , '<span class="demo-reload layui-hide" style="display:none;" data-index="' + index + '">重传</span>'
  128. , '<span class="demo-delete">删除</span>'
  129. , '</td>'
  130. , '</tr>'].join(''));
  131. // 以二进制方式打开文件
  132. console.log(file);
  133. fileReader.readAsBinaryString(file);
  134. //单个重传
  135. tr.find('.demo-reload').on('click', function () {
  136. var idx = $(this).data('index');
  137. obj.upload(idx, file);
  138. });
  139. //删除
  140. tr.find('.demo-delete').on('click', function () {
  141. delete files[index]; //删除对应的文件
  142. tr.remove();
  143. if(demoListView.find('tr').length==1){
  144. demoListView.append('<tr class="upload-file-none"><td colspan="5" style="color:#999;">请点击【添加文件】按钮,选择需要上传的文件</td></tr>');
  145. }
  146. else{
  147. boxh=boxh-44;
  148. }
  149. boxt=(bodyh-boxh)/2;
  150. layer.style(layerIndex, {
  151. height:boxh,
  152. top:boxt
  153. });
  154. $('.layui-layer-content').css({'height':'auto'});
  155. uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
  156. });
  157. demoListView.append(tr);
  158. if($('.upload-file-none').length>0){
  159. $('.upload-file-none').remove();
  160. }
  161. else{
  162. boxh=boxh+44;
  163. }
  164. boxt=(bodyh-boxh)/2;
  165. layer.style(layerIndex, {
  166. height:boxh,
  167. top:boxt
  168. });
  169. $('.layui-layer-content').css({'height':'auto'});
  170. });
  171. }
  172. , done: function (res, index, upload) {
  173. if (res.code == 1) { //上传成功
  174. var tr = demoListView.find('tr#upload-' + index)
  175. , tds = tr.children();
  176. tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
  177. uploadId.push(res.data.id);
  178. tds.eq(4).html('<a class="demo-del" data-index="' + (uploadId.length - 1) + '">删除</a>');
  179. return delete this.files[index]; //删除文件队列已经上传成功的文件
  180. }
  181. this.error(index, upload);
  182. },
  183. progress: function (index, file, percent) {
  184. $('#progress_' + index).html(percent * 100 + '%');
  185. var tr = demoListView.find('tr#upload-' + index)
  186. , tds = tr.children();
  187. tds.eq(2).html('<span style="color: #5FB878;">上传中...</span>');
  188. console.log(index);
  189. console.log(percent);
  190. }
  191. , error: function (index, upload) {
  192. var tr = demoListView.find('tr#upload-' + index)
  193. , tds = tr.children();
  194. $('#progress_' + index).html('0%');
  195. tds.eq(2).html('<span style="color: #FF5722;">上传失败,请重试</span>');
  196. tds.eq(4).find('.demo-reload').show(); //显示重传
  197. }
  198. });
  199. $('.upload-close-btn').on('click',function(){
  200. layer.confirm('您确定要取消上传吗?', {icon: 3, title:'提示'}, function(index){
  201. layer.closeAll();
  202. });
  203. });
  204. }
  205. });
  206. }
  207. var upload = {
  208. config: {} //全局配置项
  209. //设置全局项
  210. ,set: function(options){
  211. var that = this;
  212. that.config = $.extend({}, that.config, options);
  213. return that;
  214. }
  215. }
  216. ,device = function(key){
  217. var agent = navigator.userAgent.toLowerCase()
  218. //获取版本号
  219. ,getVersion = function(label){
  220. var exp = new RegExp(label + '/([^\\s\\_\\-]+)');
  221. label = (agent.match(exp)||[])[1];
  222. return label || false;
  223. }
  224. //返回结果集
  225. ,result = {
  226. os: function(){ //底层操作系统
  227. if(/windows/.test(agent)){
  228. return 'windows';
  229. } else if(/linux/.test(agent)){
  230. return 'linux';
  231. } else if(/iphone|ipod|ipad|ios/.test(agent)){
  232. return 'ios';
  233. } else if(/mac/.test(agent)){
  234. return 'mac';
  235. }
  236. }()
  237. ,ie: function(){ //ie版本
  238. return (!!win.ActiveXObject || "ActiveXObject" in win) ? (
  239. (agent.match(/msie\s(\d+)/) || [])[1] || '11' //由于ie11并没有msie的标识
  240. ) : false;
  241. }()
  242. ,weixin: getVersion('micromessenger') //是否微信
  243. };
  244. //任意的key
  245. if(key && !result[key]){
  246. result[key] = getVersion(key);
  247. }
  248. //移动设备
  249. result.android = /android/.test(agent);
  250. result.ios = result.os === 'ios';
  251. result.mobile = (result.android || result.ios) ? true : false;
  252. return result;
  253. }
  254. //操作当前实例
  255. ,thisUpload = function(){
  256. var that = this;
  257. return {
  258. upload: function(files){
  259. that.upload.call(that, files);
  260. }
  261. ,reload: function(options){
  262. that.reload.call(that, options);
  263. }
  264. ,config: that.config
  265. }
  266. }
  267. //字符常量
  268. ,MOD_NAME = 'upload', ELEM = '.layui-upload', THIS = 'layui-this', SHOW = 'layui-show', HIDE = 'layui-hide', DISABLED = 'layui-disabled'
  269. ,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'
  270. //构造器
  271. ,Class = function(options){
  272. var that = this;
  273. that.config = $.extend({}, that.config, upload.config, options);
  274. that.render();
  275. };
  276. //默认配置
  277. Class.prototype.config = {
  278. accept: 'images' //允许上传的文件类型:images/file/video/audio
  279. ,exts: '' //允许上传的文件后缀名
  280. ,auto: false //是否选完文件后自动上传
  281. ,bindAction: '' //手动上传触发的元素
  282. ,url: '' //上传地址
  283. ,field: 'file' //文件字段名
  284. ,acceptMime: '' //筛选出的文件类型,默认为所有文件
  285. ,method: 'post' //请求上传的 http 类型
  286. ,data: {} //请求上传的额外参数
  287. ,drag: true //是否允许拖拽上传
  288. ,size: 0 //文件限制大小,默认不限制
  289. ,number: 0 //允许同时上传的文件数,默认不限制
  290. ,multiple: false //是否允许多文件上传,不支持ie8-9
  291. };
  292. //初始渲染
  293. Class.prototype.render = function(options){
  294. var that = this
  295. ,options = that.config;
  296. options.elem = $(options.elem);
  297. options.bindAction = $(options.bindAction);
  298. that.file();
  299. that.events();
  300. };
  301. //追加文件域
  302. Class.prototype.file = function(){
  303. var that = this
  304. ,options = that.config
  305. ,elemFile = that.elemFile = $([
  306. '<input class="'+ ELEM_FILE +'" type="file" accept="'+ options.acceptMime +'" name="'+ options.field +'"'
  307. ,(options.multiple ? ' multiple' : '')
  308. ,'>'
  309. ].join(''))
  310. ,next = options.elem.next();
  311. if(next.hasClass(ELEM_FILE) || next.hasClass(ELEM_FORM)){
  312. next.remove();
  313. }
  314. //包裹ie8/9容器
  315. if(device.ie && device.ie < 10){
  316. options.elem.wrap('<div class="layui-upload-wrap"></div>');
  317. }
  318. that.isFile() ? (
  319. that.elemFile = options.elem
  320. ,options.field = options.elem[0].name
  321. ) : options.elem.after(elemFile);
  322. //初始化ie8/9的Form域
  323. if(device.ie && device.ie < 10){
  324. that.initIE();
  325. }
  326. };
  327. //ie8-9初始化
  328. Class.prototype.initIE = function(){
  329. var that = this
  330. ,options = that.config
  331. ,iframe = $('<iframe id="'+ ELEM_IFRAME +'" class="'+ ELEM_IFRAME +'" name="'+ ELEM_IFRAME +'" frameborder="0"></iframe>')
  332. ,elemForm = $(['<form target="'+ ELEM_IFRAME +'" class="'+ ELEM_FORM +'" method="post" key="set-mine" enctype="multipart/form-data" action="'+ options.url +'">'
  333. ,'</form>'].join(''));
  334. //插入iframe
  335. $('#'+ ELEM_IFRAME)[0] || $('body').append(iframe);
  336. //包裹文件域
  337. if(!options.elem.next().hasClass(ELEM_FORM)){
  338. that.elemFile.wrap(elemForm);
  339. //追加额外的参数
  340. options.elem.next('.'+ ELEM_FORM).append(function(){
  341. var arr = [];
  342. $.each(options.data, function(key, value){
  343. value = typeof value === 'function' ? value() : value;
  344. arr.push('<input type="hidden" name="'+ key +'" value="'+ value +'">')
  345. });
  346. return arr.join('');
  347. }());
  348. }
  349. };
  350. //异常提示
  351. Class.prototype.msg = function(content){
  352. alert(content);
  353. };
  354. //判断绑定元素是否为文件域本身
  355. Class.prototype.isFile = function(){
  356. var elem = this.config.elem[0];
  357. if(!elem) return;
  358. return elem.tagName.toLocaleLowerCase() === 'input' && elem.type === 'file'
  359. }
  360. //预读图片信息
  361. Class.prototype.preview = function(callback){
  362. var that = this;
  363. if(window.FileReader){
  364. $.each(that.chooseFiles, function(index, file){
  365. var reader = new FileReader();
  366. reader.readAsDataURL(file);
  367. reader.onload = function(){
  368. callback && callback(index, file, this.result);
  369. }
  370. });
  371. }
  372. };
  373. //执行上传
  374. Class.prototype.upload = function(files, type){
  375. var that = this
  376. ,options = that.config
  377. ,elemFile = that.elemFile[0]
  378. //高级浏览器处理方式,支持跨域
  379. ,ajaxSend = function(){
  380. var successful = 0, aborted = 0
  381. ,items = files || that.files || that.chooseFiles || elemFile.files
  382. ,allDone = function(){ //多文件全部上传完毕的回调
  383. if(options.multiple && successful + aborted === that.fileLength){
  384. typeof options.allDone === 'function' && options.allDone({
  385. total: that.fileLength
  386. ,successful: successful
  387. ,aborted: aborted
  388. });
  389. }
  390. };
  391. $.each(items, function(index, file){
  392. var formData = new FormData();
  393. formData.append(options.field, file);
  394. //追加额外的参数
  395. $.each(options.data, function(key, value){
  396. value = typeof value === 'function' ? value() : value;
  397. formData.append(key, value);
  398. });
  399. //提交文件
  400. var opts = {
  401. url: options.url
  402. ,type: 'post' //统一采用 post 上传
  403. ,data: formData
  404. ,contentType: false
  405. ,processData: false
  406. ,dataType: 'json'
  407. ,headers: options.headers || {}
  408. //成功回调
  409. ,success: function(res){
  410. successful++;
  411. done(index, res);
  412. allDone();
  413. }
  414. //异常回调
  415. ,error: function(){
  416. aborted++;
  417. that.msg('请求上传接口出现异常');
  418. error(index);
  419. allDone();
  420. }
  421. };
  422. //监听进度条
  423. if(typeof options.progress === 'function'){
  424. opts.xhr = function(){
  425. var xhr = $.ajaxSettings.xhr();
  426. //监听上传进度
  427. xhr.upload.addEventListener("progress", function (e) {
  428. if(e.lengthComputable) {
  429. var percent = Math.floor((e.loaded/e.total)* 100); //百分比
  430. options.progress(percent, options.item[0], e);
  431. }
  432. });
  433. return xhr;
  434. }
  435. }
  436. $.ajax(opts);
  437. });
  438. }
  439. //低版本IE处理方式,不支持跨域
  440. ,iframeSend = function(){
  441. var iframe = $('#'+ ELEM_IFRAME);
  442. that.elemFile.parent().submit();
  443. //获取响应信息
  444. clearInterval(Class.timer);
  445. Class.timer = setInterval(function() {
  446. var res, iframeBody = iframe.contents().find('body');
  447. try {
  448. res = iframeBody.text();
  449. } catch(e) {
  450. that.msg('获取上传后的响应信息出现异常');
  451. clearInterval(Class.timer);
  452. error();
  453. }
  454. if(res){
  455. clearInterval(Class.timer);
  456. iframeBody.html('');
  457. done(0, res);
  458. }
  459. }, 30);
  460. }
  461. //统一回调
  462. ,done = function(index, res){
  463. that.elemFile.next('.'+ ELEM_CHOOSE).remove();
  464. elemFile.value = '';
  465. if(typeof res !== 'object'){
  466. try {
  467. res = JSON.parse(res);
  468. } catch(e){
  469. res = {};
  470. return that.msg('请对上传接口返回有效JSON');
  471. }
  472. }
  473. typeof options.done === 'function' && options.done(res, index || 0, function(files){
  474. that.upload(files);
  475. });
  476. }
  477. //统一网络异常回调
  478. ,error = function(index){
  479. if(options.auto){
  480. elemFile.value = '';
  481. }
  482. typeof options.error === 'function' && options.error(index || 0, function(files){
  483. that.upload(files);
  484. });
  485. }
  486. ,exts = options.exts
  487. ,check ,value = function(){
  488. var arr = [];
  489. $.each(files || that.chooseFiles, function(i, item){
  490. arr.push(item.name);
  491. });
  492. return arr;
  493. }()
  494. //回调返回的参数
  495. ,args = {
  496. //预览
  497. preview: function(callback){
  498. that.preview(callback);
  499. }
  500. //上传
  501. ,upload: function(index, file){
  502. var thisFile = {};
  503. thisFile[index] = file;
  504. that.upload(thisFile);
  505. }
  506. //追加文件到队列
  507. ,pushFile: function(){
  508. that.files = that.files || {};
  509. $.each(that.chooseFiles, function(index, item){
  510. that.files[index] = item;
  511. });
  512. return that.files;
  513. }
  514. //重置文件
  515. ,resetFile: function(index, file, filename){
  516. var newFile = new File([file], filename);
  517. that.files = that.files || {};
  518. that.files[index] = newFile;
  519. }
  520. }
  521. //提交上传
  522. ,send = function(){
  523. //选择文件的回调
  524. if(type === 'choose' || options.auto){
  525. options.choose && options.choose(args);
  526. if(type === 'choose'){
  527. return;
  528. }
  529. }
  530. //上传前的回调
  531. options.before && options.before(args);
  532. //IE兼容处理
  533. if(device.ie){
  534. return device.ie > 9 ? ajaxSend() : iframeSend();
  535. }
  536. ajaxSend();
  537. }
  538. //校验文件格式
  539. value = value.length === 0
  540. ? ((elemFile.value.match(/[^\/\\]+\..+/g)||[]) || '')
  541. : value;
  542. if(value.length === 0) return;
  543. switch(options.accept){
  544. case 'file': //一般文件
  545. if(exts && !RegExp('\\w\\.('+ exts +')$', 'i').test(escape(value))){
  546. that.msg('选择的文件中包含不支持的格式');
  547. return elemFile.value = '';
  548. }
  549. break;
  550. case 'video': //视频文件
  551. if(!RegExp('\\w\\.('+ (exts || 'avi|mp4|wma|rmvb|rm|flash|3gp|flv') +')$', 'i').test(escape(value))){
  552. that.msg('选择的视频中包含不支持的格式');
  553. return elemFile.value = '';
  554. }
  555. break;
  556. case 'audio': //音频文件
  557. if(!RegExp('\\w\\.('+ (exts || 'mp3|wav|mid') +')$', 'i').test(escape(value))){
  558. that.msg('选择的音频中包含不支持的格式');
  559. return elemFile.value = '';
  560. }
  561. break;
  562. default: //图片文件
  563. $.each(value, function(i, item){
  564. if(!RegExp('\\w\\.('+ (exts || 'jpg|png|gif|bmp|jpeg$') +')', 'i').test(escape(item))){
  565. check = true;
  566. }
  567. });
  568. if(check){
  569. that.msg('选择的图片中包含不支持的格式');
  570. return elemFile.value = '';
  571. }
  572. break;
  573. }
  574. //检验文件数量
  575. that.fileLength = function(){
  576. var length = 0
  577. ,items = files || that.files || that.chooseFiles || elemFile.files;
  578. $.each(items, function(){
  579. length++;
  580. });
  581. return length;
  582. }();
  583. if(options.number && that.fileLength > options.number){
  584. return that.msg('同时最多只能上传的数量为:'+ options.number);
  585. }
  586. //检验文件大小
  587. if(options.size > 0 && !(device.ie && device.ie < 10)){
  588. var limitSize;
  589. $.each(that.chooseFiles, function(index, file){
  590. if(file.size > 1024*options.size){
  591. var size = options.size/1024;
  592. size = size >= 1 ? (size.toFixed(2) + 'MB') : options.size + 'KB'
  593. elemFile.value = '';
  594. limitSize = size;
  595. }
  596. });
  597. if(limitSize) return that.msg('文件不能超过'+ limitSize);
  598. }
  599. send();
  600. };
  601. //重置方法
  602. Class.prototype.reload = function(options){
  603. options = options || {};
  604. delete options.elem;
  605. delete options.bindAction;
  606. var that = this
  607. ,options = that.config = $.extend({}, that.config, upload.config, options)
  608. ,next = options.elem.next();
  609. //更新文件域相关属性
  610. next.attr({
  611. name: options.name
  612. ,accept: options.acceptMime
  613. ,multiple: options.multiple
  614. });
  615. };
  616. //事件处理
  617. Class.prototype.events = function(){
  618. var that = this
  619. ,options = that.config
  620. //设置当前选择的文件队列
  621. ,setChooseFile = function(files){
  622. that.chooseFiles = {};
  623. $.each(files, function(i, item){
  624. var time = new Date().getTime();
  625. that.chooseFiles[time + '-' + i] = item;
  626. });
  627. }
  628. //设置选择的文本
  629. ,setChooseText = function(files, filename){
  630. var elemFile = that.elemFile
  631. ,value = files.length > 1
  632. ? files.length + '个文件'
  633. : ((files[0] || {}).name || (elemFile[0].value.match(/[^\/\\]+\..+/g)||[]) || '');
  634. if(elemFile.next().hasClass(ELEM_CHOOSE)){
  635. elemFile.next().remove();
  636. }
  637. that.upload(null, 'choose');
  638. if(that.isFile() || options.choose) return;
  639. elemFile.after('<span class="layui-inline '+ ELEM_CHOOSE +'">'+ value +'</span>');
  640. };
  641. //点击上传容器
  642. options.elem.off('upload.start').on('upload.start', function(){
  643. var othis = $(this), data = othis.attr('lay-data');
  644. if(data){
  645. try{
  646. data = new Function('return '+ data)();
  647. that.config = $.extend({}, options, data);
  648. } catch(e){
  649. hint.error('Upload element property lay-data configuration item has a syntax error: ' + data)
  650. }
  651. }
  652. that.config.item = othis;
  653. that.elemFile[0].click();
  654. });
  655. //拖拽上传
  656. if(!(device.ie && device.ie < 10)){
  657. options.elem.off('upload.over').on('upload.over', function(){
  658. var othis = $(this)
  659. othis.attr('lay-over', '');
  660. })
  661. .off('upload.leave').on('upload.leave', function(){
  662. var othis = $(this)
  663. othis.removeAttr('lay-over');
  664. })
  665. .off('upload.drop').on('upload.drop', function(e, param){
  666. var othis = $(this), files = param.originalEvent.dataTransfer.files || [];
  667. othis.removeAttr('lay-over');
  668. setChooseFile(files);
  669. if(options.auto){
  670. that.upload(files);
  671. } else {
  672. setChooseText(files);
  673. }
  674. });
  675. }
  676. //文件选择
  677. that.elemFile.off('upload.change').on('upload.change', function(){
  678. var files = this.files || [];
  679. setChooseFile(files);
  680. options.auto ? that.upload() : setChooseText(files); //是否自动触发上传
  681. });
  682. //手动触发上传
  683. options.bindAction.off('upload.action').on('upload.action', function(){
  684. that.upload();
  685. });
  686. //防止事件重复绑定
  687. if(options.elem.data('haveEvents')) return;
  688. that.elemFile.on('change', function(){
  689. $(this).trigger('upload.change');
  690. });
  691. options.elem.on('click', function(){
  692. if(that.isFile()) return;
  693. $(this).trigger('upload.start');
  694. });
  695. if(options.drag){
  696. options.elem.on('dragover', function(e){
  697. e.preventDefault();
  698. $(this).trigger('upload.over');
  699. }).on('dragleave', function(e){
  700. $(this).trigger('upload.leave');
  701. }).on('drop', function(e){
  702. e.preventDefault();
  703. $(this).trigger('upload.drop', e);
  704. });
  705. }
  706. options.bindAction.on('click', function(){
  707. $(this).trigger('upload.action');
  708. });
  709. options.elem.data('haveEvents', true);
  710. };
  711. //核心入口
  712. upload.render = function(options){
  713. var inst = new Class(options);
  714. return thisUpload.call(inst);
  715. };