[学习笔记]
图片不自动上传并在表单提交时再上传,看代码。
附上表单页面
前台实现
<#--图片名-->
<input id="fileName" type="text" lay-verify="fileName"
autocomplete="off" class="layui-input" disabled>
<#--隐藏输入框 用来存放上传后图片路径-->
<input id="credential_hide" name="credentialOne" type="hidden" lay-verify="credentialOne"
autocomplete="off" class="layui-input">
<#--隐藏按钮 上传-->
<button id="upload_img" type="button" hidden></button>
<button class="layui-btn" id="preview_img" type="button">
上传图片
</button>
<button class="layui-btn layui-btn-normal btn-submit" id="fake">
确定
</button>
<#---->
layui.use(['form', 'layer', 'upload'], function () {
$ = layui.jquery;
var form = layui.form,
layer = layui.layer,
upload = layui.upload;
/*上传图片*/
upload.render({
elem: '#preview_img'
, url: 'upload'
, size: 1024
, auto: false //不自动上传
, bindAction: '#upload_img' //上传绑定到隐藏按钮
, choose: function (obj) {
//预读本地文件
obj.preview(function (index, file, result) {
$('#fileName').val(file.name); //展示文件名
})
}
, done: function (res) {
$('#credential_hide').val(res.msg); //隐藏输入框赋值
$('#submitForm').click(); //上传成功后单击隐藏的提交按钮
}
, error: function (index, upload) {
layer.msg('上传失败!' + index, {icon: 5});
}
});
//确定按钮点击事件
$('#fake').click(function () {
$(this).attr({'disabled': 'disabled'});
$('#upload_img').click();//单击隐藏的上传按钮
});
/*监听提交*/
form.on('submit(add_recharge_submit)', function (data) {
addRecharge(data.field);
return false;
});
});
后台上传接口
@ApiOperation("凭据上传")
@PostMapping(value = "upload")
@ResponseBody
public JsonUtil imgUpload(@RequestParam("file") MultipartFile file) {
JsonUtil j = new JsonUtil();
String fileName = uploadPathURL + uploadUtil.upload(file);
j.setMsg(fileName);
return j;
}
在图片预览处,我加了折叠面板以及点击查看大图,需要的可以参考。
<#--折叠面板-->
<div class="layui-collapse" lay-accordion="" style=" 399.5px">
<div class="layui-colla-item">
<h2 class="layui-colla-title">展开图片</h2>
<div class="layui-colla-content" id="colla_img" style="">
</div>
</div>
</div>
choose回调做一些调整
choose: function (obj) {
obj.preview(function (index, file, result) {
$('#fileName').val(file.name); //展示文件名
$('#colla_img').find('img').remove();
$('#colla_img').append('<a href="#" onclick="openImg();"><img id="showImg" src="' + result + '" width="370px"></a>');
})
}
/*查看大图*/
function openImg() {
var idBar = '#showImg';
var src = $(idBar)[0].src;
var width = $(idBar).width();
var height = $(idBar).height();
var scaleWH = width / height;
var bigH = 550;
var bigW = scaleWH * bigH;
if (bigW > 1000) {
bigW = 1000;
bigH = bigW / scaleWH;
} // 放大预览图片
parent.layer.open({
type: 1,
title: false,
closeBtn: 1,
shadeClose: true,
area: [bigW + 'px', bigH + 'px'], //宽高
content: '<img width="' + bigW + '" src="' + src + '" />'
});
}
文章转载自原文:https://blog.csdn.net/kerw1nKwan/article/details/90411628