我使用React-Dropzone
的Dropzone
组件与 Nextjs 和 TypeScript。
如果文件大小超过 30MB(30000000
字节),我想拒绝上传。
目前,当将大文件放入区域时-出现此错误:
我看到有一个名为onDropRejected
的属性与Dropzone
组件在这个documentation中使用,但是我们如何使用这个而不是像上面那样遇到错误?
下面是我的 UI 的样子:
My code:type Props = {
name?: string;
isError?: boolean;
onChange?: (id: string) => void;
};
export const FileUploader = ({ name, isError, onChange }: Props) => {
const [uploading, setUploading] = useState(false);
const [nameFile, setNameFile] = useState<string>('File format: CSV Maximum upload size: 30MB');
const [currId, setCurrId] = useState('');
useEffect(() => {
name && setNameFile(name);
}, [name]);
const handleDrop = async (acceptedFiles: File[]) => {
setUploading(true);
const file = acceptedFiles[0];
const res = await AssetA.create(file, AssetResourceType.marketingAction);
if (res.id) {
setNameFile(file.name);
onChange?.(res.id);
currId && (await AssetA.remove(currId));
setCurrId(res.id);
}
setUploading(false);
};
return (
<div>
<Dropzone
onDrop={handleDrop}
multiple={false}
accept={['image/*', 'text/csv']}
disabled={uploading}
maxSize={30000000}>
{({ getRootProps, getInputProps }) => (
<div
{...getRootProps({ clName: 'dropzone' })}
clName='flex items-center w-full h-40 text-center'>
<input {...getInputProps()} />
<div
clName={clNames(
'rounded flex h-full items-center justify-center flex-col flex-1 border border-dashed text-gray-700 mr-2.5 py-6',
isError ? 'border-danger' : 'border-gray'
)}>
<Icon name='upload' size={20} />
<div clName='mb-2.5 text-medium'>Drag and drop to upload</div>
<on
type='on'
clName='px-2.5 border-gray-700 border rounded-full text-small px-3 py-0.5'>
Select file
</on>
<div clName='mt-2 text-gray-500 text-small'>{nameFile}</div>
</div>
</div>
)}
</Dropzone>
</div>
);
};
您可以添加一个函数验证器:
const fileValidator = (file) => {
if (file.size > 30000000) {
return {
code: "size-too-large",
message: `file is larger than 30MB`,
};
}
return null;
}
然后,在您的 useDropZone 中添加您的函数:
const { getRootProps, getInputProps, isDragAccept, isDragReject } =
useDropzone({
onDrop,
validator: fileValidator,
});
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(40条)