如何在beforeUpload里面判断图片的格式大小尺寸
BeforeUpload (file) {
let _this = this
// 为什么用new Promise,如果不用的话,判断尺寸img.onload是异步的,不等判断完成,就会自动完成图片上传
return new Promise((resolve, reject) => {
const isAllow = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 <= 0.5
if (!isAllow) {
this.$message.error('图片只能是JPEG、JPG、PNG格式!')
return reject(false)
}
if (!isLt2M) {
this.$message.error('上传图片不能大于500k!')
return reject(false)
}
// 判断尺寸是否符合要求
if (isAllow && isLt2M) {
let img = new Image()
img.src = URL.createObjectURL(file)
img.onload = function () {
let { width = 0, height = 0 } = img || {}
if (Number((width/height).toFixed(1)) !== 16/10) {
_this.$message({
type: 'error',
message: `尺寸不符合 16:10 的要求,请处理后添加`
})
return reject(false)
} else {
return resolve(true)
}
}
}
})
}