由于项目需要,图片上传需要进行压缩之后在调用接口,那就只能走自定义上传
自定义上传关键在于:
action = #
:auto-upload="false"
<el-upload
ref="upload"
action="#" // 上传入口改成 #
:multiple="true" // 多文件上传开启
:on-change="handleChange" // 改变监听
:file-list="fileList" //文件列表
:auto-upload="false" // 自动上传关闭
>
<i class="el-icon-plus"></i>
</el-upload>
由于 auto-upload 设置为 false 之后,before-upload 会失效,所以上传的事件之前体现在 change 里。
但是这样呢在上传文件时无论是多图还是单图,在上传后都会走2次 handleChange ,
此时我们需要一个防抖方法,来限制它。
handleChange(file, fileList) {
/*
自动上传改成true会导致重复触发,所以在handleChange上传文件
*/
// 防抖
let length = fileList.length
this.maxLength = Math.max(length, this.maxLength)
setTimeout(() => {
if (length === this.maxLength) {
// 你的上传文件逻辑
}
}, 100)
}
this.maxLength 默认设置 0 就行,要记得在上传成功(完成)后需要设置为默认 0。
下面附上我完整的代码
change 事件
handleChange(file, fileList) {
/*
自动上传改成true会导致重复触发,所以在handleChange上传文件
*/
// 防抖
let length = fileList.length
this.maxLength = Math.max(length, this.maxLength)
setTimeout(() => {
if (length === this.maxLength) {
// 图片验证
this.uploadFilesVerification(fileList)
}
}, 100)
}
图片验证: uploadFilesVerification
// 图片验证
async uploadFilesVerification(fileList) {
let resFileList = []
for (const key in fileList) {
console.log('fileList[key] :>> ', fileList[key])
// 判断文件大小(5M)
if (fileList[key].size > 1024 * 1024 * 5) {
this.$message.warning('图片大小不可以超过5M')
return
}
// 图片压缩(这里用的 lrz,项目不需要可以忽略)
const lrzData = await lrz(fileList[key].raw, { quality: 0.5 })
// 内容验证
// xxxx
resFileList.push(lrzData.origin)
}
// 上传图片
this.customUploadFn(resFileList)
}
自定义上传:customUploadFn
扫描二维码关注公众号,回复:
14989543 查看本文章
// 自定义上传
async function customUploadFn(fileList) {
let form = new FormData()
fileList.forEach((item) => {
form.append('files', item)
})
const { data } = await uploadFiles(form) // 上传 api 接口
console.log('data :>> ', data)
data.forEach((item) => {
this.goodsImgList.push(item) // 图片回显数组
})
this.fileList = [] // 清空图片已经上传的图片列表(绑定在上传组件的file-list)
this.maxLength = 0 // 恢复默认值
}
以上是 element 自定义 多文件上传 触发多次on-change 的解决方案。