Reputation: 559
I'm using Dropzone
component of React-Dropzone
with Nextjs and TypeScript.
I want to reject the upload if the file size is over 30MB (30000000
Bytes). The reject message could be whatever at this point.
Currently, when dropping a big file into the zone - this error appears:
I saw that there is a property called onDropRejected
to use with Dropzone
component in this documentation but how can we use this one instead of running into the error like above?
Here's how my UI looks like:
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 AssetApis.create(file, AssetResourceType.marketingAction);
if (res.id) {
setNameFile(file.name);
onChange?.(res.id);
currId && (await AssetApis.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({ className: 'dropzone' })}
className='flex items-center w-full h-40 text-center'>
<input {...getInputProps()} />
<div
className={classNames(
'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 className='mb-2.5 text-medium'>Drag and drop to upload</div>
<button
type='button'
className='px-2.5 border-gray-700 border rounded-full text-small px-3 py-0.5'>
Select file
</button>
<div className='mt-2 text-gray-500 text-small'>{nameFile}</div>
</div>
</div>
)}
</Dropzone>
</div>
);
};
Upvotes: 0
Views: 3793
Reputation: 21
you can add a function validator :
const fileValidator = (file) => {
if (file.size > 30000000) {
return {
code: "size-too-large",
message: `file is larger than 30MB`,
};
}
return null;
}
And then, add your function in your useDropZone :
const { getRootProps, getInputProps, isDragAccept, isDragReject } =
useDropzone({
onDrop,
validator: fileValidator,
});
Upvotes: 2