React Uploader Hook is a hook simply for file upload
It can be used with react-dropzone or a simple <input type="file"/>
The key is calling the onDrop(files) with FileList or an array of File
// npm
npm install react-uploader-hook
// or yarn
yarn add react-uploader-hookimport React, {useCallback} from 'react';
import useFileUploader from 'react-uploader-hook';
const App = () => {
const getUploadParams = useCallback((file) => {
// [💡] you can return custom request configurations here
const form = new FormData();
form.append('file', file);
return {
method: 'post',
url: 'https://file.io?expires=1w',
headers: {'Content-Type': 'multipart/form-data'},
data: form,
meta: {'any-other-stuff': 'hello'},
};
}, []);
const onUploaded = useCallback((fileBag) => {
// [💡] do whatever with the uploaded files
}, []);
// [⭐]
const {onDrop, fileBags} = useFileUploader({getUploadParams, onUploaded});
const handleChange = useCallback(
(event) => {
onDrop(event.target.files);
},
[onDrop],
);
return (
<div>
<input type="file" onChange={handleChange} />
<pre>{JSON.stringify(fileBags, null, 2)}</pre>
</div>
);
};useFileUploader() takes in an object of type FileUploaderProps as an argument
export interface FileUploaderProps {
getUploadParams: (file: File) => Promise<UploadParams> | UploadParams;
onUploaded?: (fileBag: FileBag) => void;
onFailed?: (fileBag: FileBag) => void;
}This is a callback function that will be called before a request is sent to the server to upload each file. The function must return an object in the following shape
export interface UploadParams {
url: string;
method: 'put' | 'post' | 'patch' | string;
headers?: {[key: string]: any};
data?: any; // the file to upload or FormData in the case of multipart form
meta?: {[key: string]: any}; // any extra data to forward to the FileBag.meta
}This function will be called on successful upload of each file. The first argument will be fileBag, a wrapper object for the uploaded file
the status field will contain the value 'uploaded' and 'progress' 100
export interface FileBag {
id: string;
file: File;
uploadUrl: string;
progress: number; // 0 - 100
formattedSize: string;
status: 'uploading' | 'uploaded' | 'failed';
httpStatus: number; // 200, 404 etc.
message: string;
responseData: any; // the response body from the server
meta?: {[key: string]: any}; // any extra data forwarded from getUploadParams()
}Similar to onUploaded(), however the status will be 'failed'. httpStatus and responseData would
contain additional information to know why the upload failed.
Call this function to trigger an upload. It accepts File[] or FileList as argument
Call this function to retry a failed upload. It accepts the fileBag id as argument