0
0
ReactDebug / FixBeginner · 4 min read

How to Handle File Upload in React: Simple Guide

In React, handle file upload by using an <input type='file'> element with an onChange handler to capture the selected file. Then, use FormData to send the file to a server via fetch or axios.
🔍

Why This Happens

Many beginners try to upload files in React by directly reading the input value or sending the file object incorrectly, which causes errors or no file being sent.

This happens because file inputs are special and their value is read-only; you must access the file from the files property of the input event target.

jsx
import React, { useState } from 'react';

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

  const handleChange = (e) => {
    // Incorrect: trying to get file from e.target.value
    setFile(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('File to upload:', file);
    // This will not work because file is a string, not a File object
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" onChange={handleChange} />
      <button type="submit">Upload</button>
    </form>
  );
}

export default FileUpload;
Output
File to upload: C:\fakepath\myfile.txt
🔧

The Fix

To fix this, access the file from e.target.files[0] inside the onChange handler. Then use FormData to send the file in a POST request.

This ensures you get the actual file object and can upload it properly.

jsx
import React, { useState } from 'react';

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

  const handleChange = (e) => {
    setFile(e.target.files[0]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!file) return alert('Please select a file first');

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch('/upload', {
        method: 'POST',
        body: formData
      });
      if (response.ok) {
        alert('File uploaded successfully');
      } else {
        alert('Upload failed');
      }
    } catch (error) {
      alert('Error uploading file');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" onChange={handleChange} aria-label="File upload input" />
      <button type="submit">Upload</button>
    </form>
  );
}

export default FileUpload;
Output
When a file is selected and the form submitted, an alert shows 'File uploaded successfully' if the server responds OK.
🛡️

Prevention

Always access files from e.target.files instead of e.target.value. Use FormData to send files in POST requests. Add aria-label for accessibility on file inputs. Validate file selection before upload to avoid errors.

Use linting tools like ESLint with React plugins to catch common mistakes early.

⚠️

Related Errors

1. Sending file as JSON: Trying to send a file by JSON.stringify causes errors because files are binary data.

2. Not using FormData: Uploads fail if you send files as plain text or URL encoded data.

3. Missing enctype on form: When using plain HTML forms, forgetting enctype="multipart/form-data" prevents file upload.

Key Takeaways

Use e.target.files[0] to get the selected file from the input event.
Wrap the file in FormData to send it properly in a POST request.
Validate file selection before uploading to avoid errors.
Add accessibility labels to file inputs for better user experience.
Avoid sending files as JSON or plain text; always use FormData.