Coding exercise: create a file upload component in React.

React practical coding · Freshers and experienced

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

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