Springboot中layui.upload上传文件后页面前端立即刷新显示
程序员文章站
2022-04-08 12:59:55
...
html中代码:
<div class="col-md-6 column">
<div class="form-group">
<label for="bt-financeIdentityCardBack">身份证反面:</label>
<br>
<button type="button" class="layui-btn "
id="bt-financeIdentityCardBack">
<i class="fa fa-cloud"></i>上传文件
</button>
<br>
<input id="financeIdentityCardBack"
name="financeIdentityCardBack"
type="hidden" th:value="${cDO.financeIdentityCardBack}">
<div class="file-box">
<div class="file">
<a href="#">
<span class="corner"></span>
<div class="image">
<img alt="身份证反面" id="financeIdentityCardBackImg"
class="img-responsive" src="">
</div>
<a class="btn btn-warning btn-xs"
href="" id="financeIdentityCardBackViewBtn"
target="_blank">查看</a>
</a>
</div>
</div>
</div>
</div>
js代码:
//进入页面立即执行
$(function(){
var financeIdentityCardBack=$("#financeIdentityCardBack").val();
$("#financeIdentityCardBackImg").attr("src",financeIdentityCardBack);
$("#financeIdentityCardBackViewBtn").attr("href",financeIdentityCardBack);
});
layui.use('upload', function () {
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#bt-financeIdentityCardBack',//绑定元素接口
url: '/companyInfo/upload', //上传接口
size: 102400,
accept: 'file',
data:{"type":"身份证反面"},
done: function (r) {
layer.msg(r.msg);
$("#financeIdentityCardBack").val(r.fileName);
$("#financeIdentityCardBackImg").attr("src",r.fileName);
$("#financeIdentityCardBackViewBtn").attr("href",r.fileName);
},
error: function (r) {
layer.msg(r.msg);
}
});
});
controller代码:
@ResponseBody
@PostMapping("/upload")
R upload(@RequestParam("file") MultipartFile file,@RequestParam("type") String type,Model model) {
String fileName = file.getOriginalFilename();
fileName = FileUtil.renameToUUID(fileName);
Long companyId = companyUserService.getCompanyId(ShiroUtils.getUser().getUserId());
CompanyInfoDO cDO = companyInfoService.get(companyId);
FileDO sysFile = new FileDO(FileType.fileType(fileName), "/files/" + fileName, new Date());
try {
FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
//上传到磁盘之后,然后再返回这个路径
if("身份证反面".equals(type)){
cDO.setFinanceIdentityCardBack("/files/"+fileName);
}
} catch (Exception e) {
return R.error();
}
return R.error("上传文件失败!");
}
FileUtil是bootdo框架中的一个工具类