Client Hooks
Better Upload provides React hooks that allow you to easily upload files using pre-signed URLs. Multipart uploads are managed automatically, in case you enable them in the server.
Usage
import { useUploadFile } from 'better-upload/client';
export function MyComponent() {
const {
upload,
uploadAsync,
reset,
uploadedFile,
progress,
isPending,
isSettled,
isError,
isSuccess,
error,
metadata,
control, // for use in pre-built components
} = useUploadFile({
route: 'demo',
});
return (
<input
type="file"
onChange={(e) => {
if (e.target.files?.[0]) {
upload(e.target.files[0]);
}
}}
/>
);
}
If your upload route handler is not located at /api/upload
, you need to
specify the correct path in the api
option.
Options
The useUploadFile
hook accepts the following options:
Prop | Type | Default |
---|---|---|
route | string | - |
api? | string | /api/upload |
multipartBatchSize? | number | All parts at once |
signal? | AbortSignal | - |
headers? | HeadersInit | - |
Events
On before upload
Callback that is called before requesting the pre-signed URL. Use this to modify the file before uploading it, like resizing or compressing. You can also throw an error to reject the file upload.
useUploadFile({
route: 'demo',
onBeforeUpload: ({ file }) => {
// rename the file
return new File([file], 'renamed-' + file.name, { type: file.type });
},
});
On upload begin
Event that is called before the file starts being uploaded to S3. This happens after the server responds with the pre-signed URL.
useUploadFile({
route: 'demo',
onUploadBegin: ({ file, metadata }) => {
console.log('Upload begin');
},
});
On upload progress
Event that is called when the file upload progress changes.
useUploadFile({
route: 'demo',
onUploadProgress: ({ file }) => {
console.log(`Upload progress: ${file.progress * 100}%`);
},
});
On upload complete
Event that is called after the file is successfully uploaded.
useUploadFile({
route: 'demo',
onUploadComplete: ({ file, metadata }) => {
console.log('File uploaded');
},
});
On error
Event that is called if the upload fails.
useUploadFile({
route: 'demo',
onError: (error) => {
console.log(error.message);
},
});
This event is also called if some input is invalid. For example, if no files were selected.
On upload settle
Event that is called after the upload settles (either successfully completed or an error occurs).
useUploadFile({
route: 'demo',
onUploadSettle: ({ file, metadata }) => {
console.log('Upload settled');
},
});