React File Upload with Progress Bar
Upload files in React with a progress bar using XMLHttpRequest and FormData. Supports drag-and-drop, multiple files, file type validation, and upload.
Code
import { useState, useRef } from 'react';
export function FileUpload({ url, accept }: { url: string; accept?: string }) {
const [progress, setProgress] = useState(0);
const xhrRef = useRef<XMLHttpRequest | null>(null);
const upload = (file: File) => {
const formData = new FormData();
formData.append('file', file);
const xhr = new XMLHttpRequest();
xhrRef.current = xhr;
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) setProgress(Math.round((e.loaded / e.total) * 100));
};
xhr.open('POST', url);
xhr.send(formData);
};
const cancel = () => xhrRef.current?.abort();
return (
<div>
<input type="file" accept={accept} onChange={(e) => e.target.files?.[0] && upload(e.target.files[0])} />
<progress value={progress} max={100} />
<button onClick={cancel}>Cancel</button>
</div>
);
}What the code does
React File Upload with Progress Bar keeps everything in the functions upload, cancel and FileUpload.
The import line is the dependency contract: useState, useRef come from react and nothing else.
What to watch for
- Plan for an install step:
reactis a real dependency, resolved by the package manager.
Using it
The main signature reads export function FileUpload({ url, accept }: { url: string; accept?: string })
The surface worth importing is FileUpload; the helpers around it are private to the snippet.
Key statements
<input type="file" accept={accept} onChange={(e) => e.target.files?.[0] && upload(e.target.files[0])} />
<progress value={progress} max={100} />
<button onClick={cancel}>Cancel</button>
</div>
);
const cancel = () => xhrRef.current?.abort();
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) setProgress(Math.round((e.loaded / e.total) * 100));
};
FAQ
- What does this need from the package registry?
- These are real dependencies: `react`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.