antd upload文件格式 大小 尺寸校验
warning:
这篇文章距离上次修改已过187天,其中的内容可能已经有所变动。
在使用Ant Design的Upload组件时,可以通过beforeUpload属性自定义文件上传前的验证逻辑,以下是一个实例代码,展示了如何在上传文件之前进行格式和尺寸的验证:
import React from 'react';
import { Upload, message, Icon } from 'antd';
import { UploadFile } from 'antd/lib/upload/interface';
function beforeUpload(file: UploadFile) {
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;
}
const UploadDemo = () => (
<Upload
name="file"
beforeUpload={beforeUpload}
onChange={info => {
if (info.file.status === 'done') {
message.success('File uploaded successfully');
}
}}
>
<Icon type="plus" /> Click to upload
</Upload>
);
export default UploadDemo;
在这个例子中,beforeUpload函数检查了文件的类型和大小。如果文件不符合规定的格式或尺寸,它会使用Ant Design的message组件显示错误消息,并返回false阻止文件上传。如果文件通过验证,则返回true允许上传。
评论已关闭