在写需求的时候要进行宽高的校验,再进行上传,可以使用promise来进行判断,是继续resolve()还是reject()
使用示例 (直接上代码)
beforeUpload = (file) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG/PNG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
}
return isJpgOrPng && isLt2M && this.checkImageWH(file, 710, 180);
}
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 || height && this.height != height) {
message.error(
'请上传' + width + "*"+ height + '的图片'
)
reject();
} else {
resolve();
}
};
image.onerror = reject;
image.src = src;
};
filereader.readAsDataURL(file);
});
}
<Upload
name="avatar"
className = {styles.inlinebannerpic}
listType="picture-card"
showUploadList={false}
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
beforeUpload={this.beforeUpload}
onChange={this.handleChange}
>
{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
</Upload>
方便以后直接复用!!!!