Coding exercise: create a file upload component in React.
Model answer
Use a file input, check type and size in the browser for a quick message, send it as FormData (do not set Content-Type yourself, the browser adds the boundary), and show progress or a status. The server must check the file again.
function Upload() {
const [status, setStatus] = useState('');
const [preview, setPreview] = useState('');
const pick = async (e) => {
const file = e.target.files[0];
if (!file) return;
if (!['image/png', 'image/jpeg'].includes(file.type)) return setStatus('Only PNG or JPG.');
if (file.size > 2 * 1024 * 1024) return setStatus('Maximum size is 2 MB.');
setPreview(URL.createObjectURL(file));
const body = new FormData();
body.append('file', file);
setStatus('Uploading…');
const res = await fetch('/api/upload', { method: 'POST', body });
setStatus(res.ok ? 'Uploaded.' : 'Upload failed.');
};
useEffect(() => () => preview && URL.revokeObjectURL(preview), [preview]);
return (<>
<input type="file" accept="image/png,image/jpeg" onChange={pick} />
{preview && <img src={preview} alt="Selected" width="120" />}
<p role="status">{status}</p>
</>);
}For real progress bars use XMLHttpRequest or axios, which report upload progress; fetch does not.
Tips
- On the Node side, mention multer and checking the real file type, not just the extension.
Practise it yourself in the React and Angular code playground.
Learn this topic
React.js Full Course: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in React.
- Coding exercise: create a search box with debounce in React.
- Coding exercise: fetch API data and display it in a table in React.
- Coding exercise: implement pagination in React.
- Coding exercise: create a login form with validation in React.
- Coding exercise: build a parent-child communication example in React.