handleBeforeUpload(file, fileList) {
// fileList 只包含了当次上传的文件列表,不包含已上传的文件列表
// 所以长度要加上已上传的文件列表的长度
const isLimit = this.fileList.length + fileList.length > this.limit;
const indexOfFile = fileList.findIndex(item => item.uid === file.uid) + this.fileList.length;
if (isLimit && indexOfFile === this.limit) {
file.status = 'beforeUploadReject';
file.statusText = '最多上传' + this.limit + '张图片';
return false;
}
if (isLimit && indexOfFile > this.limit) {
file.status = 'beforeUploadReject';
return false;
}
const isJpgOrPng = file.type.startsWith('image/');
if (!isJpgOrPng) {
file.status = 'beforeUploadReject';
file.statusText = '请上传图片';
return false;
}
const isLtmb = file.size / 1024 / 1024 < this.isLtMB;
if (!isLtmb) {
file.status = 'beforeUploadReject';
file.statusText = `图片不能大于${this.isLtMB}mb`;
return false;
}
let self = this;
if (this.limitHeight && this.limitWidth) {
return new Promise((resolve, reject) => {
// 图片宽高比例限制
let w = 0,
h = 0;
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const image = new Image();
image.src = reader.result;
image.onload = () => {
w = image.width;
h = image.height;
if (w > self.limitWidth || h > self.limitHeight) {
self.$message.error('图片尺寸超过限制,请重新上传');
return reject(false);
} else {
return resolve(true);
}
};
};
});
}
},
异步操作要用promise返回true或者false