Skip to content

Commit

Permalink
docs: restrict file size in client-side upload example
Browse files Browse the repository at this point in the history
  • Loading branch information
robinzigmond committed Dec 6, 2023
1 parent 5a75d03 commit 9388b8c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/components/file-input/file-input.stories.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ to track upload progress on the server, or do not actually send the files to a s
Note the use of a `ref` to store the `FileReader` object - this is not essential but avoids having to create a new `FileReader` object more than once in the
lifecycle of the component.

This example also contains validation to restrict the user from uploading large files - this is useful because storing a large file in memory may make the
browser freeze or even crash. If your application needs to process large files on the client side then consider
[reading the file into an ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer) and processing that piece-by-piece.

<Canvas>
<Story name="tracking upload status on client side" story={stories.UploadStatusClient} />
</Canvas>
Expand Down
13 changes: 13 additions & 0 deletions src/components/file-input/file-input.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export const FileTypeValidation: ComponentStory<typeof FileInput> = () => {
};

export const UploadStatusClient: ComponentStory<typeof FileInput> = () => {
const [error, setError] = useState<string | undefined>();
const [uploadStatus, setUploadStatus] = useState<
FileUploadStatusProps | undefined
>();
Expand All @@ -136,11 +137,21 @@ export const UploadStatusClient: ComponentStory<typeof FileInput> = () => {

const onChange = (files: FileList) => {
if (!files.length) {
setError(undefined);
removeFile();
return;
}
// as this is a single file input there will only ever be (at most) 1 file
const fileUploaded = files[0];

// abandon with error if the file is too big
if (fileUploaded.size > 5 * 1024 * 1024) {
setError("This file is too big to be uploaded - maximum size 5MB");
return;
}

setError(undefined);

const fileReader = getReader();

const handleLoad = () => {
Expand Down Expand Up @@ -215,8 +226,10 @@ export const UploadStatusClient: ComponentStory<typeof FileInput> = () => {
return (
<FileInput
label="Upload status example"
inputHint="Maximum size 5MB"
onChange={onChange}
uploadStatus={uploadStatus}
error={error}
/>
);
};
Expand Down

0 comments on commit 9388b8c

Please sign in to comment.