当前位置: 首页 > Web前端 > HTML5

layui文件上传的中断处理

时间:2023-04-04 22:54:05 HTML5

最近在做项目的时候,遇到一个需求,在上传文件的过程中,需要判断文件是否已经存在。如果存在,让用户决定是否继续上传。这里需要注意两点:文件是否存在,需要调用后台接口返回结果,涉及异步问题;是否继续上传,需要在上传回调函数中传入returnfalse,防止文件继续上传。首先,我的想法是在before回调中打断。我使用的layui版本是v2.5.6。低版本需要修改upload.js的源码,y=function(){return"choose"===i?l.choose&&l.choose(g):((l.before&&l.before(g))===false?'':o.ie?o.ie>9?u():c():无效你())};然后在页面一步步写上上传相关的业务代码:upload.render({elem:'#chooseBtn',url:'XXXXX',accept:'file',exts:'xls|excel|xlsx',headers:{token:localStorage.getItem('token')},data:{},before:function(obj){varflag=true;layer.load();//上传加载文件=obj.pushFile();this.data={institution:$("#dropdownMenu1").val(),handle_class:$("#handle_class").val(),file_name:files[fileId].name}obj.preview(函数(索引,文件,结果){file_name=file.namefileId=索引;$("#fileWrap").append(''+file.name+'上传中')$.ajax({url:'mon/monitor/clean/checkUpload.json',contentType:'application/x-www-form-urlencoded',type:'post',beforeSend:function(request){request.setRequestHeader('token',localStorage.getItem('token'));},data:{institution:$("#dropdownMenu1").val(),file_name:文件。name},dataType:"json",//服务器返回的数据类型为jsonsuccess:function(data){if(data.code=='100'){$('#chooseBtn').css('显示','无')标志=真}其他{if(data.code=='104'){layer.confirm(data.msg+',点击OK替换原文件',{title:'Prompt',btn:['Cancel','OK']},function(index){//做一些事情deletefiles[fileId];$("#fileWrap").find('li[id="'+fileId+'"]').remove();layer.close(index);flag=false返回false},function(index){flag=trueobj.upload(fileId,file)$('#chooseBtn').css('display','none')});返回假}否则{flag=falselayer.msg(data.msg)}}},错误:function(data){flag=falseconsole.error(data)}})});返回标志},完成:函数(res,index,upload){console.log(res,index)layer.closeAll('loading');//关闭加载},error:function(index,upload){layer.closeAll('loading');//关闭加载删除文件[index];$("#fileWrap").find('li[id="'+index+'"]').remove();$("#chooseBtn").css('display','inline-block')}});这看起来没什么问题,但实际上,选择文件后立即上传文件,去重判断的接口甚至在文件上传成功后返回结果。上传文件前的flag读到的其实是初始值true,所以不阻塞上传过程。后来我尝试把去重改成同步async:false,把去重赋值给一个函数。最后在before中返回这个函数,结果flag虽然变成了期望值false,但是仍然没有停止上传过程……经过多次尝试,我有了一个想法。由于立即上传不起作用,您可以尝试触发按钮上传。这样做的好处是实际上只执行选择文件的回调,点击设置的上传切换按钮后才会执行选择文件回调。之前,做ne,报错这些回调,所以最终的解决方案是:选择文件后,立即进行去重判断(在choose回调中),并保存判断结果;单击上传按钮并立即决定(使用去重结果)是否继续上传代码FYIvarfiles=null;varfileId='';varfile_name='';varflag=true;varuploadInst=upload.render({elem:'#chooseBtn',url:'XXX',accept:'file',auto:false,bindAction:'#startBtn',exts:'xls|excel|xlsx',标题:{token:localStorage.getItem('token')},data:{},xhr:xhrOnProgress,//pass导入监听函数!importantchoose:function(obj){$("#startBtn").css('display','inline-block')files=obj.pushFile();obj.preview(function(index,file,result){file_name=file.namefileId=index;$("#fileWrap").append(''+file.name+'上传

')element.render('progress','progressBar'+fileId);$.ajax({url:'xxx',contentType:'application/x-www-form-urlencoded',type:'post',async:false,beforeSend:function(request){request.setRequestHeader('token',localStorage.getItem('token'));},data:{机构:$("#dropdownMenu1").val(),file_name:file.name},dataType:"json",success:function(data){if(data.code=='100'){$('#chooseBtn').css('display','none')flag=true}else{if(data.code=='104'){layer.confirm(data.msg+',点击确定将替换译文件',{title:'提示',btn:['取消删除','确定']},function(index){//做一些删除文件[fileId];$("#fileWrap").find('li[id="'+fileId+'"]').remove();图层关闭(索引);flag=falsereturnfalse},function(index){flag=trueobj.upload(fileId,file)$('#chooseBtn').css('display','none')});返回false}else{flag=falselayer.msg(data.msg)}}},错误:函数(数据){flag=falseconsole.error(数据)}})});},之前:function(obj){layer.load();//上传加载console.log('this:',this)this.data={institution:$("#dropdownMenu1").val(),handle_class:$("#handle_class").val(),file_name:files[fileId].name}returnflag},progress:function(n,elem){varpercent=n+'%'//获取进度百分比element.progress('progressBar'+fileId,percent);//可以配合layui进度条元素使用},done:function(res,index,upload){console.log(res,index)layer.closeAll('loading');//关闭加载if(files){deletefiles[index];}if(res.code=='100'){fileSuccess=true$("#fileWraplispan")[0]。innerText=文件名}else{layer.msg(res.msg)$("#fileWrap").find('li[id="'+fileId+'"]').remove();fileSuccess=false}$("#startBtn").css('显示','无');$('#chooseBtn').css('显示','内联块');},错误:函数(索引,上传){layer.closeAll('loading');//关闭加载删除文件[index];$("#fileWrap").find('li[id="'+index+'"]').remove();$("#chooseBtn").css('display','inline-block')}});$("#fileWrap").on('click','lii',function(e){varfileId=$(this).parent('li').attr("id");删除文件[fileId];$(this).parent('li').remove();$("#chooseBtn").css('display','inline-堵塞')});页面如图:点击上传开关后,点击确定后上传,否则,重新选择文件,再次触发choose回调,进行去重判断...上传成功后,uploadswitch被隐藏了然后废话多一点:进度条还需要在upload.js文件中的p.prototype.config中添加xhr,即p.prototype.config={accept:"images",exts:"",auto:!0,bindAction:"",url:"",字段:"file",acceptMime:"",method:"post",data:{},drag:!0,size:0,number:0,米ultiple:!1,xhr:function(){}}然后创建一个进度条监控函数varxhrOnProgress=function(fun){xhrOnProgress.onprogress=fun;//绑定监听//使用闭包实现监听绑定returnfunction(){//通过$.ajaxSettings.xhr()获取XMLHttpRequest对象;varxhr=$.ajaxSettings.xhr();//判断监听函数是否为函数if(typeofxhrOnProgress.onprogress!=='function')returnxhr;//如果有监听函数,并且xhr对象支持绑定,就给监听函数绑定}返回xhr;}}进度条在选择文件的预览方法中已经添加了dom,但是这里必须要激活,否则会出现虽然进度条动态变化,但是上面的文字,也就是百分比没有变化因此,所以需要这一行:element.render('progress','progressBar'+fileId);然后只需更新进度回调中的进度。今天就分享这么多吧。有更好的解决办法一起讨论~~~