实现限制图片上传格式、尺寸、分辨率的限制
官网API如下:
image.png
实现方式
//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) {
Modal.error({
title: '请上传宽为' + width + '的图片'
})
reject();
} else if (height && this.height != height) {
Modal.error({
title: '请上传高为' + height + '的图片',
})
reject();
} else {
resolve();
}
};
image.onerror = reject;
image.src = src;
};
filereader.readAsDataURL(file);
});
}
handleBeforeUpload = (file) => {
//限制图片 格式、size、分辨率
const isJPG = file.type === 'image/jpeg';
// const isJPEG = file.type === 'image/jpeg';
const isGIF = file.type === 'image/gif';
const isPNG = file.type === 'image/png';
if (!(isJPG || isGIF || isPNG)) {
Modal.error({
title: '只能上传JPG 、JPEG 、GIF、 PNG格式的图片~'
})
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
Modal.error({
title: '超过2M限制 不允许上传~'
})
}
return (isJPG || isGIF || isPNG ) && isLt2M && this.checkImageWH(file, 1268, 950);
}
<Upload
action={action}
data={{project_id: this.props.projectId}}
listType="picture-card"
fileList={fileList}
multiple={true}
showUploadList={false}
onPreview={this.handlePreview}
onChange={this.handleChange}
beforeUpload={this.handleBeforeUpload}
>
{!this.state.locaImagesShow ? null : uploadButton}
</Upload>
网友评论