多图片上传功能
<template><div class="image"><el-row :gutter="10" class="mb8"><el-col :span="1.5"><el-button type="success" plain icon="el-icon-upload" size="mini" @click="uploadFn">上传</el-button></el-col><el-col :span="1.5"><el-button type="danger" plain icon="el-icon-delete" size="mini" @click="clearFn">清空</el-button></el-col></el-row><h2>多图片上传</h2><div class="file-loading"><input type="file" multiple @change="handleFileUpload" class="input"></div><div class="concat"><div class="info" v-for="(item, index) of images" :key="index"><img :src="item.path" class="img" /><span @click="handleRemove(item)"><i class="el-icon-delete"></i></span><p>{{ item.name }}</p></div></div></div>
</template><script>
import axios from 'axios'
import { getToken } from "@/utils/auth"export default {data() {return {images: [],file: []}},methods: {handleFileUpload(event) {this.file = [...event.target.files]for (let i = 0; i < this.file.length; i++) {if (!this.file[i].type.startsWith('image/jpeg')) {this.$modal.msgError('请上传jpg格式的图片')continue}const reader = new FileReader()reader.onload = (e) => {this.images.push({ path: e.target.result, name: this.file[i].name })}reader.readAsDataURL(this.file[i])}},handleRemove(item) {this.images = this.images.filter(obj => obj.name != item.name)this.file = this.file.filter(file => file.name !== item.name)},uploadFn() {if (this.file.length == 0) {this.$modal.msgError("请先上传图片!")} else {const formData = new FormData()for (const file of this.file) {formData.append('files', file)}axios({url: process.env.VUE_APP_BASE_API + '/common/uploads',method: "post",headers: { Authorization: "Bearer " + getToken() },data: formData}).then((res) => {this.$modal.msgSuccess(res.data.msg)this.images = []this.file = []}).catch(err => {this.$modal.msgError(res.data.unExitFileNames)})}},clearFn() {if (this.file.length == 0) {this.$modal.msgError("请先上传图片!")} else {this.images = []this.file = []}}}
}
</script><style>
.image {margin: 20px;
}.concat {display: flex;flex-wrap: wrap;
}.info {text-align: center;width: 200px;height: 260px;margin: 10px;
}.img {width: 200px;height: 200px;position: relative;margin-bottom: 10px;
}.file-loading {width: 100%;height: 200px;border: 2px dashed #ccc;border-radius: 5px;display: flex;justify-content: center;align-items: center;
}.input {width: 100%;height: 180px;padding: 10px;font-size: 18px;
}
</style>