解决element-ui使用Upload组件,before-upload钩子返回false时,文件仍然上传成功的问题
AI 摘要salmon-ai
本
问题
今天做图片上传限制尺寸大小时遇到了坑,如果我们在before-upload中直接返回true或者是false,那么它其实也是会上传文件的,因为它也会触发on-success函数。
错误的做法
js
/**
* 上传文件前校验
* @param file
* @returns {Promise<boolean>}
*/
async beforeAvatarUpload(file) {
let isAccess = file.size / 1024 / 1024 < this.size;
if (!isAccess) {
this.$message.error(`上传图片大小不能超过 ${this.size} MB!`);
} else {
if (this.isNotEmpty(this.limit) && this.getFileType(file.name) === "image") {
const img = await this.readImg(file)
console.log("image ", img.width, img.height);
if (img.width !== this.limit.width && img.height !== this.limit.height) {
this.$message.error(`请上传 ${this.limit.width}px*${this.limit.height}px 尺寸的图片!`);
isAccess = false;
}
}
}
return isAccess
}
解决
我们应该使用一个Promise包起来,这样不满足条件,就不会出发on-success了。如下:
js
/**
* 上传文件前校验
* @param file
* @returns {Promise<boolean>}
*/
beforeAvatarUpload(file) {
return new Promise(async (resolve, reject) => {
if (this.isNotEmpty(this.limit) && this.getFileType(file.name) === "image") {
const img = await this.readImg(file)
console.log("image ", img.width, img.height);
if (img.width !== this.limit.width || img.height !== this.limit.height) {
this.$message.error(`请上传 ${this.limit.width}px*${this.limit.height}px 尺寸的图片!`);
return reject(false);
}
}
if (file.size / 1024 / 1024 > this.size) {
this.$message.error(`上传图片大小不能超过 ${this.size} MB!`);
return reject(false);
}
return resolve(true);
})
},
评论
0 条—
还没有评论,来说第一句