vue项目中,上传图片做像素大小宽高的限制
<el-upload
class="avatar-uploader"
action="http://upload.qiniup.com"
:data="qn"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="form.joint.imgUrlBefore" :src="form.joint.imgUrlBefore"
class="avatar" @click="getToken('imgUrlBefore','poster_url')">
<i v-else class="el-icon-plus avatar-uploader-icon"
@click="getToken('imgUrlBefore','poster_url')"></i>
</el-upload>
/**
* 上传前判断
*/
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
const isLt1M = file.size / 1024 / 1024 < 1;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
}
if (!isLt1M) {
this.$message.error('上传头像图片大小不能超过 1MB!');
}
let _this = this;
let imgWidth = "";
let imgHeight = "";
let width;
let height;
const isSize = new Promise(function (resolve, reject) {
if (_this.form.ad_type == 1) {
width = 700;
height = 300;
} else if (_this.form.ad_type == 2) {
width = 800;
height = 1280;
}
console.log(width, height);
let _URL = window.URL || window.webkitURL;
let img = new Image();
img.onload = function () {
imgWidth = img.width;
imgHeight = img.height;
let valid = img.width == width && img.height == height;
valid ? resolve() : reject();
};
img.src = _URL.createObjectURL(file);
}).then(
() => {
return file;
},
() => {
_this.$message.error({
message: '上传文件的图片大小不合符标准,宽需要为' + width + 'px,高需要为' + height + 'px。当前上传图片的宽高分别为:' + imgWidth + 'px和' + imgHeight + 'px',
btn: false
});
return Promise.reject();
});
console.log(isSize);
return isJPG && isLt1M && isSize;
},