代码:
<template>
<div class="show-img">
<ul>
<li v-for="imgSrc in imgUrl" :key="imgSrc">
<el-image
style="width: 130px; height: 130px;border-radius: 5px;"
:src="imgSrc"
:zoom-rate="1.2"
:max-scale="7"
:min-scale="0.2"
:preview-src-list="[imgSrc]"
:initial-index="4"
fit="cover"
/>
</li>
<li class="show-img-addImg" @click="callAddImg">
<el-icon>
<Plus/>
</el-icon>
</li>
</ul>
<el-button plain type="success" class="upload-button" @click="imgUpload">
上传
</el-button>
</div>
<input v-show="false" multiple="multiple" ref="addImgInput"
type="file" name="image" accept="image/*" @change="addImg">
</template>
<script setup>
import {Plus} from '@element-plus/icons-vue'
import {ref} from "vue";
import axios from "axios";
const imgArray = ref([])//存放选取的图片
const imgUrl = ref([])//图片结果
//存放 添加图片按钮
const addImgInput = ref(null)
//调用 选择添加图片 方法
const callAddImg = () => {
addImgInput.value.click()
}
//选择添加图片
const addImg = (e) => {
const newImgs = Object.values(e.target.files)
newImgs.forEach((img) => {
let reader = new FileReader();
reader.readAsDataURL(img)
reader.onload = () => {
imgUrl.value.push(reader.result)
}
})
imgArray.value = imgArray.value.concat(newImgs)
}
//图片上传服务器
const imgUpload = () => {
imgArray.value.forEach((file) => {
console.log(file)
axios({
method: 'post',
url: 'http://127.0.0.1:5000/upload-img',
headers: {"Content-Type": "multipart/form-data"},
data: {"file": file}
}).then(function (response) {
console.log(response)
})
})
}
</script>
<style scoped>
* {
user-select: none;
}
/*上传按钮*/
.upload-button {
margin-top: 20px;
float: right;
}
/*图片选项卡*/
.show-img > ul {
list-style: none;
display: flex;
align-content: flex-start;
flex-wrap: wrap;
min-height: 325px;
max-height: 70dvh;
border: 1px solid var(--border-color);
overflow-y: auto;
padding: 10px 0px;
transition: 0.5s;
}
.show-img > ul::-webkit-scrollbar {
width: 5px;
}
.show-img > ul::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 10px;
}
.show-img > ul::-webkit-scrollbar-thumb:hover {
background: #bdbdbd;
}
.show-img > ul > li {
width: 140px;
height: 140px;
margin: 5px;
padding: 5px;
border-radius: 5px;
box-sizing: border-box;
border: 1px solid var(--border-color);
}
.show-img > ul > .show-img-addImg {
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
border: 1px dashed var(--border-color);
transition: 0.5s;
}
.show-img > ul > .show-img-addImg:hover {
--hover-color: #80c5ff;
color: var(--hover-color);
border: 1px dashed var(--hover-color);
}
</style>
效果:
![](https://img-blog.csdnimg.cn/direct/f513c75d3c6c4a97bc1b2ac03e64c157.png)