一、效果如下
二、引入layui
可到layui官网下载 https://www.layui.com/
https://www.layui.com/
三、页面代码
四、后台代码
后台代码没有写逻辑,自行编写 (@RequestMapping 改为自己的即可 ,注意和前端请求保持一致)
五、代码(直接copy即可)
引入代码
前端
<link rel="stylesheet" href="${pageContext.request.contextPath}/views/static/layui-v2.6.8/layui/css/layui.css">
<script src="${pageContext.request.contextPath}/views/static/layui-v2.6.8/layui/layui.js"></script>
html代码
<div class="form-group">
<label for="imgBtn" class="col-sm-2 control-label">上传头像</label>
<div class="col-sm-10" style="width: 300px;">
<button type="button" class="layui-btn layui-btn-radius layui-btn-normal" id="imgBtn">
<i class="layui-icon"></i>上传头像
</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2" style="width: 300px;">
<div class="layui-progress" lay-showPercent="yes">
<div class="layui-progress-bar" id="uploadImg" lay-percent="0%"></div>
</div>
</div>
</div>
js代码
var element = layui.element, form = layui.form, layer = layui.layer, table = layui.table, laydate = layui.laydate, util = layui.util, tree = layui.tree , upload = layui.upload;
element.render();
layui.use('upload', function () {
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#imgBtn' //绑定元素
, url: '${pageContext.request.contextPath}/setting/user/fileUpload/' //上传接口
, done: function (res) {
//上传完毕回调
layer.alert("上传成功", {icon: 1, offset: 't'});
}
, error: function () {
//请求异常回调
}
, progress: function (n) {
var percent = n + '%' //获取进度百分比
$("#uploadImg").attr("lay-percent", percent);
element.render(); //进度条
}
});
});
后台
@RequestMapping("fileUpload")
@ResponseBody
public ResultVo fileUpload(MultipartFile file) {
ResultVo resultVo = new ResultVo();
resultVo.setOk(true);
return resultVo;
}