使用element-ui的upload上传图片,官方文档中提供了在beforePicUpload中校验图片格式和大小的方法,但是没有提供校验宽高方法。
需求:
在开发的过程中,我们可能需要限制图片的width和heigth相同,也可能需要限制width比height长,还有可能需要限制height比width长。
解决方法:
beforePicUpload (file) {
let _this = this
const isJPG = file.type === 'image/jpeg' || 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {this.$Mint.Toast('上传图片只能是jpg或者png格式!')}
if (!isLt2M) {this.$Mint.Toast('上传图片大小不能超过2MB!')}
const isSize = new Promise(function (resolve, reject) {
let _URL = window.URL || window.webkitURL
let img = new Image()
img.onload = function () {
let valid = img.width < img.height
valid ? resolve() : reject()
}
img.src = _URL.createObjectURL(file)
}).then(() => {
return file
}, () => {
_this.$Mint.Toast({
message: '请上传竖屏的图片!'
})
return Promise.reject()
})
return isJPG && isLt2M && isSize
}
如果需要上传横屏的,只需更改以下部分:
let valid = img.width > img.height
那,如果我们想要用户上传宽高相等的怎么操作呢?
beforePicUpload (file) {
let _this = this
const isJPG = file.type === 'image/jpeg' || 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {this.$Mint.Toast('上传图片只能是jpg或者png格式!')}
if (!isLt2M) {this.$Mint.Toast('上传图片大小不能超过2MB!')}
const isSize = new Promise(function (resolve, reject) {
let width = 500
let height = 500
let _URL = window.URL || window.webkitURL
let img = new Image()
img.onload = function () {
let valid = img.width === width && img.height === height
valid ? resolve() : reject()
}
img.src = _URL.createObjectURL(file)
}).then(() => {
return file
}, () => {
_this.$Mint.Toast({
message: '上传图片长宽需为500*500!!'
})
return Promise.reject()
})
return isJPG && isLt2M && isSize
}