Layui文件上传带进度条

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">&#xe67c;</i>选择文件
		</button> 文件名称: <span id="fileName"></span>
		<div style="height: 20px;"></div>
		<button type="button" class="layui-btn" id="uploadBtn">
  			<i class="layui-icon">&#xe67c;</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>

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韩淼燃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值