1.图片upload之前做监听,>-- before-upload
<div class="demo-upload-list" v-for="i in uploadImgList">
<template>
<img :src="i">
<div class="demo-upload-list-cover">
<Icon type="ios-trash-outline" @click.native="handleRemove()"></Icon>
</div>
</template>
<template v-else>
<Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
</template>
</div>
<Upload
v-if="uploadImgList.length == 0"
ref="upload"
:show-upload-list="false"
:format="['jpg','jpeg','png']"
:before-upload="handleBeforeUpload"
type="drag"
action="#"
style="display: inline-block;width:58px;">
<div style="width: 58px;height:58px;line-height: 58px;" class="upload-icon">
<Icon type="ios-camera" size="20" ></Icon>
</div>
</Upload>
handleBeforeUpload:上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。
这里会用到Promise ,及同步异步问题。
async xzhandleUpload(file) {
// 有大小限制
var isImage = false;
await this.checkImageWH(file,this.whSize).then(params => {
isImage = params;
});
if (!isImage) {
return;
}
// 图片验证通过,下一步请求上传图片
this.handleUpload(file);
},
checkImageWH--在这里就是进一步通过获取image的大小,判断上传的图片是否符合规定。
async checkImageWH(file) {
return new Promise((resolve, reject)=> {
let _this = this;
let filereader = new FileReader();
filereader.onload = (e) => {
let src = e.target.result;
const image = new Image();
image.onload = (e) => {
// w 、h设置的限制参数
if (image.width == w && image.height == h) {
resolve(true);
} else {
_this.$Notice.warning({
title: '图片尺寸为'+ this.whSize
})
reject(false);
}
};
image.onerror = reject;
image.src = src;
};
filereader.readAsDataURL(file);
}).catch((e) => {});
},