因项目需要,上传图片前要验证图片的高宽,看了一下官方文档,before-upload可以返回false或者Promise,就通过promise实现了这个功能.
(ps:里面有用到vuex保存上传七牛的设置,可以根据自己的需要增删)
下面上代码:
- test.vue html
<Upload ref="detailUpload" :show-upload-list="false" :before-upload="detailBeforeUpload" :on-success="detailSuccess" :format="['jpg','jpeg','png']" :max-size="4096" :accept="'image/*'" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :action="$store.state.qnSetting.upurl ?$store.state.qnSetting.upurl: 'http://upload-z2.qiniup.com'" :data="{token:$store.state.qnSetting.token}">
<div class="detail-camera-content">
<Icon type="camera" size="50"></Icon>
</div>
</Upload>
- test.vue js
//return promise
detailBeforeUpload(file) {
return this.checkImageWH(file, 706, 397);
}
//checkImageWH 返回一个promise 检测通过返回resolve 失败返回reject组织图片上传
checkImageWH(file, width, height) {
let self = this;
return new Promise(function (resolve, reject) {
let filereader = new FileReader();
filereader.onload = e => {
let src = e.target.result;
const image = new Image();
image.onload = function () {
if (width && this.width != width) {
self.$Notice.error({
title: '请上传宽为' + width + "的图片",
});
reject();
} else if (height && this.height != height) {
self.$Notice.error({
title: '请上传高为' + height + "的图片",
});
reject();
} else {
resolve();
}
};
image.onerror = reject;
image.src = src;
};
filereader.readAsDataURL(file);
});
}