解决多文件上传,自定义方法调用多次接口
- 1、将
<el-upload>
组件中的 auto-upload
设置为 false
。 - 2、使用
on-change
钩子对上传方法进行重写。 - 3、在方法的最后添加
return false
。
完整代码:
<template>
<el-upload
ref="uploadImg"
action
multiple
accept=".png,.jpeg,.jpg"
list-type="picture-card"
:auto-upload="false"
:file-list="uploadImg"
:on-change="handleChangeImg"
>
<span class="text">点击上传图片</span>
</el-upload>
</template>
<script>
export default {
data() {
return {
imgType: ['png', 'jpeg', 'jpg'],
uploadImg: []
}
},
methods: {
beforeUploadImg(file) {
if (file.name) {
let imgTypeIsRight = true
let imgSizeIsRight = true
const nameType = file.name.split('.')
imgTypeIsRight = this.imgType.includes(nameType[nameType.length - 1])
imgSizeIsRight = file.size / 1024 / 1024 > 2
if (!imgTypeIsRight) {
this.$message.warning(`图片格式不正确`)
}
if (imgSizeIsRight) {
this.$message.warning(`图片大小不能超过2M`)
}
return imgTypeIsRight && !imgSizeIsRight
}
},
handleChangeImg(singleFile, fileList) {
const fileFormat = this.beforeUploadImg(singleFile)
if (fileFormat) {
const hasImg = this.uploadImg.some(
(imgItem) => imgItem.uid === singleFile.uid
)
if (!hasImg) {
this.uploadImg.push({
uid: singleFile.uid,
url: singleFile.url,
pushUrl: '',
inputName: '',
inputUrl: '',
name: '',
file: singleFile
})
}
} else {
for (let i = 0; i < this.uploadImg.length; i++) {
if (this.uploadImg[i].uid === singleFile.uid) {
this.uploadImg.splice(i, 1)
}
}
}
return false
},
}
}
</script>