layui上传文件配合进度条

首先看一下效果图:

layui上传文件配合进度条

修改layui的源文件upload.js
1.打开layui/modules/upload.js
2.搜索ajax
3.找到url:
4.添加以下代码:
,xhr:l.xhr(function(e){//此处为新添加功能
var percent=Math.floor((e.loaded / e.total)*100);//计算百分比
l.progress(percent);//回调将数值返回
}) 5.upload.js 中 p.prototype.config也要改,加一个xhr的定义,否则传文件时如果不设xhr会报错 p.prototype.config={
accept:"images",exts:"",auto:!0,bindAction:"",url:""
,field:"file",method:"post",data:{},drag:!0,size:0
,number:0,multiple:!1
,xhr:function(){}//此处需要添加
},
页面js代码
layui.use(['form', 'layer', "jquery",'element', 'laydate', "upload"], function () {
var upload = layui.upload,
element=layui.element,
layer = parent.layer === undefined ? layui.layer : top.layer;
var xhrOnProgress = function (fun) {
xhrOnProgress.onprogress = fun; //绑定监听
//使用闭包实现监听绑
return function () {
//通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
var xhr = $.ajaxSettings.xhr();
//判断监听函数是否为函数
if (typeof xhrOnProgress.onprogress !== 'function')
return xhr;
//如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
if (xhrOnProgress.onprogress && xhr.upload) {
xhr.upload.onprogress = xhrOnProgress.onprogress;
}
return xhr;
}
} //选择并网时间
laydate.render({
elem: '.connectGridTime'
}); var enrollArr = [];
var demoCount=0,demoFlag=false
var demoClass //公司注册信息上传文件
upload.render({
elem: '.enroll',
accept: 'file',
multiple: true,
url: sessionStorage.getItem("imgUrl") + "picture-console/common/file/upload",
xhr: xhrOnProgress,
progress: function (value) { //上传进度回调 value进度值,由于是进度条同时又是多文件上传不只一个进度条,所以要保证每次进度条的类名不一致,demoCount控制类名,demoFlag保证上下一致,所以该方法一直在被调用
if(demoFlag){
console.log(demoCount)
element.progress(`demo${demoCount}`, value + '%') //设置页面进度条
} }, before: function (obj) {
layer.load()
obj.preview(function (index, file, result) {
layer.closeAll('loading'); //关闭loading demoCount++
console.log('before',demoCount)
var size = file.size / 1024 / 1024
if(size<=1){
size=keepTwoDecimal(size*1024)+'KB'
}else{
size=keepTwoDecimal(size)+'MB'
}
var tr=`
<tr>
<td class="fileName">${file.name}</td>
<td>${size}</td>
<td class="uploadok">
<div class="uploadLoadingDiv">
<div class="layui-progress bar" lay-showpercent="true" lay-filter="demo${demoCount}">
<div class="layui-progress-bar layui-bg-red" lay-percent="0%"><span class="layui-progress-text">100%</span></div>
</div>
</div>
</td>
<td><button class="layui-btn layui-btn-danger layui-btn-sm" onclick="registerDel(this)">删除</button></td>
</tr>
`
$('#enrollBox').append(tr);
demoFlag=true })
},
error: function(index, upload){
element.progress(`demo${demoCount}`, '0%');
layer.msg('上传失败');
},
choose:function(obj){
demoFlag=false
},
done: function (res) {
if (res.code == '200') {
enrollArr.push(res.data[0]);
}
}
});
//四舍五入保留2位小数(若第二位小数为0,则保留一位小数)
function keepTwoDecimal(num) {
var result = parseFloat(num); result = Math.round(num * 100) / 100;
return result;
} });
上一篇:C语言中如何获得文件大小


下一篇:MinGW下载并配置gcc/g++编译环境