//上传前校验方法
beforeAvatarUpload (file) {
return new Promise((resolve, reject) => {
const suffix =
file.type === 'image/jpg' ||
file.type === 'image/png' ||
file.type === 'image/jpeg'
const isLt1M = file.size / 1024 / 1024 < 1
if (!suffix) {
Message.error('上传图片只能是 JPG,PNG,JPEG 格式!')
return reject(false)
}
if (!isLt1M) {
Message.error('上传图片大小不能超过 1MB!')
return reject(false)
}
// 调用[限制图片尺寸]函数
this.limitFileWH(200, 200, file).then((res) => {
file.isFlag = res
if (file.isFlag) {
return resolve(true)
} else {
return reject(false)
}
})
})
},
控制图片尺寸方法
// 上传图片事件限制图片尺寸
limitFileWH (E_width, E_height, file) {
const _this = this
let imgWidth = ''
let imgHight = ''
const isSize = new Promise(function (resolve, reject) {
const width = E_width
const height = E_height
const _URL = window.URL || window.webkitURL
const img = new Image()
img.onload = function () {
imgWidth = img.width
imgHight = img.height
const valid = img.width === width && img.height === height
valid ? resolve() : reject()
}
img.src = _URL.createObjectURL(file)
}).then(
() => {
return true
},
() => {
Message.warning({
message:
'上传图片的尺寸应为' +
E_width +
'*' +
E_height +
',当前上传图片的尺寸为:' +
imgWidth +
'*' +
imgHight
})
return false
}
)
return isSize
},
<el-upload
:headers="headers"
class="avatar-uploader"
action="xxxxxxx"
:data="{uploadType:'userZoneImg'}"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
name="file"
/>