1.修改layui文件上传ajax的代码:
这里使用的是layui的非模块化 (layui.js),模块化请修改modules/upload.js
xhr:function () {
var newXhr = i.ajaxSettings.xhr();
// 给xhr的upload添加progress的监听
newXhr.upload.addEventListener('progress' , function (e) {
var percent = Math.floor(e.loaded / e.total * 100); //计算出进度
typeof l.progress === 'function' && l.progress(e , percent); // 传递给upload的progress回调
});
return newXhr;
},
2.页面以及upload
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传进度条</title>
<script src="../static/jquery-3.3.1.js" type="text/javascript" charset="utf-8"></script>
<script src="../static/layui.all.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="../static/css/layui.css" />
</head>
<body>
<button type="button" class="layui-btn" id="chooseFile">
<i class="layui-icon"></i>选择文件
</button> 文件名称: <span id="fileName"></span>
<div style="height: 20px;"></div>
<button type="button" class="layui-btn" id="uploadBtn">
<i class="layui-icon"></i>上传文件
</button>
<div style="height: 20px;"></div>
<div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="progressBar">
<div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
</div>
<script type="text/javascript">
var upload = layui.upload,
element = layui.element;
element.init();
upload.render({
elem: '#chooseFile', // 文件选择
accept:'file',
url: '/fileUpload',
auto: false, // 设置不自动提交
bindAction: '#uploadBtn', // 提交按钮
progress: function(e , percent) {
console.log("进度:" + percent + '%');
element.progress('progressBar',percent + '%');
},
choose: function(obj) {
obj.preview(function(index, file, result) {
$("#fileName").html(file.name);
});
},
done: function(res) {
layer.msg(res.msg);
},
error: function(res) {
layer.msg(res.msg);
}
});
</script>
</body>
</html>