html
<div class="form-group" id="imgItem" style="margin-bottom: 0;">
<label class="col-sm-3 control-label is-required">上传图片:</label>
<input type="hidden" name="pictureList" id="pictureList">
<button type="button" id="importModel" class="layui-hide">图片导入</button>
<div class="layui-input-inlines-self" id="imgItemInfo">
<div class="layui-upload-drag-self" id="importImg0">
<div id="imgDivs0">
<i class="layui-icon" id="uploadIcon0">  </i>
</div>
<div class="img layui-hide" id="uploadDemoView0">
<img class="layui-upload-img" id="imgs0" th:src="@{item}">
<div class="handle" id="handle0">
<i class="layui-icon icon-myself" id="preImg0"></i>
<i class="layui-icon icon-myself" id="delImg0"></i>
</div>
</div>
</div>
</div>
</div>
js
layui.use(['form', 'layer', 'upload'], function () {
var $ = layui.jquery,
layer = layui.layer,
form = layui.form,
upload = layui.upload;
//删除图片
$(document).on('click', '[id^=delImg]', function () {
var imgUrl = $(this).parent().parent().parent().find('img').attr('src');
// 判断 picture中是否有,有的话删掉
var pictureListString = $('#pictureList').val()
var pictureList = pictureListString.split(',');
// 判断图片列表中是否包含当前图片的URL
if (pictureList.includes(imgUrl)) {
// 找到当前图片的位置
var index = pictureList.indexOf(imgUrl);
// 从图片列表中删除当前图片的URL
pictureList.splice(index, 1);
// 将更新后的图片列表转换回字符串形式
pictureListString = pictureList.join(',');
// 将更新后的图片列表存储到表单元素中
$('#pictureList').val(pictureListString);
}
// 删除图片
var importImgF = $('#imgItemInfo').find('div:first');//importImg0、importImg1、importImg2
var empt = $(this).parent().parent().parent();//importImg0、importImg1、importImg2
var nextImgSrc = $(this).parent().parent().parent().next().find('img').attr('src');//src
//判断当前DIV后面的div的url是否为空
if (!nextImgSrc) {
//判断是否为第一个
if (importImgF.attr('id') === empt.attr('id')) {
//-是 ,清空第一个 最后面的删除
//图片url清空
empt.find('img').attr('src','');
$(this).parent().parent().addClass('layui-hide');
importImgF.find('i:first').removeClass('layui-hide');
count--;
$('#' + 'importImg' + count).remove();
} else {
// -否,删除当前
empt.remove();
}
} else {
//如果有值删除当前div
empt.remove();
}
return false;
});
$(document).on('click', '[id^=preImg]', function () {
var imgUrl = $(this).parent().parent().find('img:first').attr('src');
// var iHtml = "<img src='" + imgUrl + "' style='max-width: 100%; max-height: 100%;'/>"; // 使用max-width和max-height属性实现等比例放大
// layer.open({
// type: 1,
// shade: false,
// title: false, //不显示标题
// content: iHtml //捕获的元素,注意:最好该指定的元素要存放在body最外层,否则可能被其它的相对元素所影响
// });
layer.photos({
photos: {
"title": "附件", //相册标题
"id": 123, //相册id
"start": 0, //初始显示的图片序号,默认0
"data": [ //相册包含的图片,数组格式
{
"alt": "附件",
"pid": 666, //图片id
"src": imgUrl, //原图地址
"thumb": imgUrl //缩略图地址
}
]
},
anim: 5 //0-6的选择,指定弹出图片动画类型,默认随机(请注意,3.0之前的版本用shift参数)
});
return false;
});
//图片绑定鼠标悬浮
$(document).on("mouseenter", ".img", function () {
// 鼠标悬浮时显示图标
$(this).find('.handle');
}).trigger("mouseenter");
var imgsId,
uploadDemoViewId,
uploadIconId;
$(document).on('click', '[id^=imgDivs]', function () {
//给id赋值
uploadIconId = $(this).find('i').attr('id');
uploadDemoViewId = $(this).next().attr('id');
imgsId = $(this).next().find('img').attr('id');
$('#importModel').click();
});
var count = 1;
upload.render({
elem: '#importModel'
, multiple: false
, url: ctx + "common/uploadMultis" //改成您自己的上传接口
,auto: false
,choose: function (obj) { //选择文件后的回调
var files = obj.pushFile();
var filesArry = [];
for (var key in files) { //将上传的文件转为数组形式
filesArry.push(files[key])
}
var index = filesArry.length - 1;
var file = filesArry[index]; //获取最后选择的图片,即处理多选情况
if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1]
.replace(/[ ]/g, "").replace("MSIE", "")) < 9) {
return obj.upload(index, file)
}
canvasDataURL(file, function (blob) {
var aafile = new File([blob], file.name, {
type: file.type
})
var isLt1M;
if (file.size < aafile.size) {
isLt1M = file.size
} else {
isLt1M = aafile.size
}
if (isLt1M / 1024 / 1024 > 2) {
return layer.alert('上传图片过大!')
} else {
if (file.size < aafile.size) {
return obj.upload(index, file)
}
obj.upload(index, aafile)
}
})
}
, done: function (res) {
if (res.code !== 0) {
return layer.msg('上传失败')
}
$('#' + imgsId).attr('src', ctx + res['filePaths']);
$('#' + uploadDemoViewId).removeClass('layui-hide');
$('#' + uploadIconId).addClass('layui-hide');
$('#imgItemInfo').append(
'<div class="layui-upload-drag-self" id="importImg' + count + '">' +
'<div id="imgDivs' + count + '">' +
'<i class="layui-icon" id="uploadIcon' + count + '">  </i>' +
'</div>' +
'<div class="img layui-hide" id="uploadDemoView' + count + '">' +
'<img class="layui-upload-img" id="imgs' + count + '" src="">' +
'<div class="handle" id="handle' + count + '">' +
'<i class="layui-icon icon-myself" id="preImg' + count + '"></i>' +
'<i class="layui-icon icon-myself" id="delImg' + count + '"></i>' +
'</div>' + '</div>' + '</div>'
);
let pictureListInput = $('#pictureList').val();
let pictureUrl = res['filePaths'];
let pictureList = [];
if (!$.common.isEmpty(pictureListInput)){
pictureList = pictureListInput.split(','); // 将逗号分隔的字符串转换为数组
}
pictureList.push(pictureUrl); //向数组中添加新元素
let newPictureListInput = pictureList.join(','); // 将数组转换为逗号分隔的字符串
$('#pictureList').val(newPictureListInput); // 将新字符串存储在 <input> 元素中
count++;
}
});
function canvasDataURL(file, callback) { // 压缩转化为 base64
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
const img = new Image();
const quality = 0.8; // 图像质量
const canvas = document.createElement('canvas');
const drawer = canvas.getContext('2d');
img.src = this.result;
img.onload = function () {
const MAX_WIDTH = 1920; // 设定最大宽度为 1920px
const MAX_HEIGHT = 1080; // 设定最大高度为 1080px
let width = img.width;
let height = img.height;
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
canvas.width = width;
canvas.height = height;
drawer.drawImage(img, 0, 0, width, height);
convertBase64UrlToBlob(canvas.toDataURL(file.type, quality), callback);
}
}
}
function convertBase64UrlToBlob(urlData, callback) { //将base64转化为文件格式
const arr = urlData.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
callback(new Blob([u8arr], {
type: mime
}));
}
form.on('submit(getUrls-form-submit)', function (data) {
//使用data.field获取不到值
var imgs = $('[id^=imgs]');
var imgArray=[];
imgs.each(function () {
var url=$(this).attr('src');
//滤空
if (url){
imgArray.push(url);
}
});
alert(JSON.stringify(imgArray));
return false;
});
//也可绑定单击事件获取url数组
/* $('#getUrls').on('click',function () {
var imgs = $('[id^=imgs]');
var imgArray=[];
imgs.each(function () {
var url=$(this).attr('src');
//滤空
if (url){
imgArray.push(url);
}
});
alert(JSON.stringify(imgArray));
return false;
})*/
});
css
<style>
.layui-upload-drag-self {
background-color: #fbfdff;
border: 1px dashed #c0ccda;
border-radius: 6px;
box-sizing: border-box;
width: 148px;
height: 148px;
line-height: 148px;
vertical-align: top;
display: inline-block;
text-align: center;
cursor: pointer;
outline: 0;
margin-right: 13px;
margin-top: 13px;
float: left;
}
.layui-input-inlines-self {
position: relative;
margin-left: 0px;
min-height: 36px;
text-align: left;
}
.layui-upload-drag-self .layui-icon {
font-size: 28px;
color: #8c939d
}
.layui-upload-drag-self .img {
position:relative;
height: 148px;
width: 148px;
}
.layui-upload-img {
width: 148px;
height: 148px;
border-radius: 6px;
margin-top: -3px;
margin-left: -2px;
}
.handle {
position: absolute;
width: 148px;
height: 100%;
z-index: 100;
border-radius: 6px;
top: 0;
background: rgba(59, 60, 61, 0.09);
text-align: center;
}
.handle .icon-myself {
z-index: 999;
transition: all .3s;
cursor: pointer;
font-size: 25px;
width: 25px;
color: rgba(255, 255, 255, 0.91);
margin: 0 4px;
}
</style>
java
@PostMapping("/uploadMultis")
@ResponseBody
public AjaxResult uploadFileMultis(MultipartFile[] file) {
if (file == null) return AjaxResult.error("上传文件为空");
try {
String uploadPath = RuoYiConfig.getUploadPath();
StringBuilder filePaths = new StringBuilder();
StringBuilder fileNames = new StringBuilder();
for (MultipartFile file1 : file) {
String path = FileUploadUtils.upload(uploadPath, file1);
String name = file1.getOriginalFilename();
fileNames.append(name).append("|");
filePaths.append(path).append("|");
}
AjaxResult ajax = AjaxResult.success();
ajax.put("filePaths", filePaths.deleteCharAt(filePaths.lastIndexOf("|")).toString());
ajax.put("fileNames", fileNames.deleteCharAt(fileNames.lastIndexOf("|")).toString());
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}