Interview Q&A / React

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How do you read a file from an input type file in React?

SHORT ANSWER

File inputs are always uncontrolled. Read e.target.files in onChange, take the File object, and either upload it with FormData or preview it with URL.createObjectURL. You cannot set a file input's value from state.

Explain it simply

For security, browsers do not let JavaScript set which file an input holds, so you cannot control it with value. You can only read what the user picked.

In onChange, e.target.files is a list. Take files[0] and keep it in state. To preview an image, make a temporary URL with URL.createObjectURL(file). To upload, append it to a FormData object and send with fetch; do not set the Content-Type header yourself, since the browser adds the right multipart boundary.

Validate type and size on the client for a better experience, and again on the server for safety.

Example

jsx
function Upload() {
  const [file, setFile] = useState(null);

  async function send() {
    const body = new FormData();
    body.append("resume", file);
    await fetch("/api/upload", { method: "POST", body });
  }

  return (
    <>
      <input type="file" accept="application/pdf" onChange={e => setFile(e.target.files[0])} />
      <button disabled={!file} onClick={send}>Upload</button>
    </>
  );
}

What to say in the interview

"A file input is uncontrolled. I read e.target.files in onChange, keep the File in state, and send it through FormData without manually setting the content type. I check size and type on the client for feedback and on the server for security."

Common mistakes

  • Manually setting Content-Type to multipart/form-data, which removes the boundary.

#forms#file-upload

Related questions

Practise more React questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open React quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.