首页 > 解决方案 > AntD Upload在裁剪图片前需要验证

问题描述

我想上传方形图像,我想验证图像类型。我有以下代码。此代码在图像被裁剪后验证。但我想在图像加载之前验证模态中的裁剪。

AntD组件

<ImgCrop rotate>
                  <Upload
                    listType="picture-card"
                    customRequest={onFileChange}
                    fileList={fileList}
                    onChange={onChange}
                    onPreview={onPreview}
                    beforeUpload={beforeUpload}
                    maxCount={1}
                    onRemove={onRemove}
                  >
                    {fileList.length < 1 && "+ Upload"}
                  </Upload>
</ImgCrop>

验证功能

function 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;

}

标签: reactjsantd

解决方案


您应该在ImgCrop中使用道具 beforeCrop 验证图像

beforeCrop:模态打开前调用,如果返回false,则不打开


推荐阅读