今天刚接了一个新需求,上传图片需要限制图片的宽高,容差在10像素。
这块是上传的大小不合适就提示:请准确上传广告图,像素要求是380px*100px,1200px*158px,所以我就直接写死了。
看下我上传图像的尺寸:
具体代码如下:
<el-upload
class="heightCredential"
:action="action"
:file-list="list"
:show-file-list="isList"
:on-success="handleSuccess"
:before-upload="beforeUpload">
<i v-show="!isList && list.length" class="el-icon-close img-close" @click.stop="clearFile"></i>
</el-upload>
beforeUpload(file) {
return new Promise((resolve, reject) => {
const FileExt = file.name.replace(/.+\./, '').toLowerCase()
const isLt2M = file.size / 1024 / 1024 < this.size
const fileArr = this.accept.replace(/\./g, '').toLowerCase().split(',')
const imageExt = ['jpg', 'png', 'webp', 'jpeg', 'bmp', 'gif'];
const fileCheck = () => {
if (fileArr.indexOf(FileExt) === -1) {
reject(this.$message({
type: 'warning',
message: `请上传后缀名为${fileArr.join('/')}的文件!`
}))
}
this.$emit('beforeUpload',true)
if (!isLt2M) {
this.$emit('beforeUpload',false)
reject(this.$_toast({type: 'error', msg: `文件大小不能超过${this.size}MB`}));
}
resolve(true);
}
//如果是图片
if(this.isDesign == '广告设计'){ // 上传像素是(380px*100px,1200px*158px)
if(imageExt.includes(FileExt)) {
const _URL = window.URL || window.webkitURL
const img = new Image();
img.src = _URL.createObjectURL(file);
img.onload = () => {
// let [imgWidth, imgHeight] = this.sizeRule;
let arrWidth = [380,1200]
let baseWidth = arrWidth.sort((a, b)=> {
return Math.abs(a - img.width ) - Math.abs(b - img.width );
})[0];
console.log(baseWidth);
// 380px*100px,1200px*158px
if ( baseWidth==1200 && (Math.abs(img.width - 1200)>10 || Math.abs(img.height - 158)>10)) reject(
this.$message.warning(`请准确上传广告图`)
)
if (baseWidth==380 && (Math.abs(img.width - 380)>10 || Math.abs(img.height - 100)>10)) reject(
this.$message.warning(`请准确上传广告图`)
)
fileCheck();
}
}else fileCheck();
}else if (imageExt.includes(FileExt) && this.sizeRule.length) { //上传像素固定值
const _URL = window.URL || window.webkitURL
const img = new Image();
img.src = _URL.createObjectURL(file);
img.onload = () => {
let [imgWidth, imgHeight] = this.sizeRule;
if (this.sizeRule.length && (img.width !== imgWidth || img.height !== imgHeight)) reject(
this.$message.warning(`请上传尺寸为 ${imgWidth}px * ${imgHeight}px 的图片`)
)
fileCheck();
}
} else fileCheck();
})
},
这里主要是在before-upload,执行的,(before-upload:上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。)
在两个像素尺寸这块主要是判断了上传图片的宽跟那个更那个更接近让后再做容差判断。