實現(xiàn)限制圖片上傳格式、尺寸、分辨率的限制
官網(wǎng)API如下:

image.png
實現(xiàn)方式
//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>