DEV Community

Cover image for Day 18 of 100 Days of Code — Understanding File Uploads in React
M Saad Ahmad
M Saad Ahmad

Posted on

Day 18 of 100 Days of Code — Understanding File Uploads in React

Today was Day 18 of my 100 Days of Code, and the topic I focused on was File Uploading on the Frontend.
Even though I’m learning it within React, file uploading itself is not a new or React-specific concept. The process is actually the same as plain HTML — the difference lies in how JavaScript and React process those files afterward.


📁 Basic File Uploading in React (Same as HTML)

React does not change how file inputs work. Files are uploaded using the regular <input> tag:

<input type="file" accept="image/*" />
<input type="file" accept=".pdf,.docx" />
<input type="file" multiple />
Enter fullscreen mode Exit fullscreen mode

What accept means:

  • accept="image/*" → only images can be selected
  • accept=".pdf,.docx" → restrict to PDF and DOCX
  • multiple → allow selecting more than one file

🔍 Accessing the Uploaded File in React

When the user selects a file, we capture it using onChange:

const handleFileChange = (e) => {
  const file = e.target.files[0]; // files is an array if multiple=true
  console.log(file); // File { name, size, type, ... }
};
Enter fullscreen mode Exit fullscreen mode

The File object includes metadata like:

  • name
  • size
  • type
  • lastModified

🖼️ Previewing the Uploaded File (Especially Images)

If you want to show a preview before uploading, you can use:

URL.createObjectURL(file) → creates a temporary local URL for the file.

Example:

const [preview, setPreview] = useState(null);

const handleFileChange = (e) => {
  const file = e.target.files[0];
  setPreview(URL.createObjectURL(file));
};
Enter fullscreen mode Exit fullscreen mode

JSX:

<img src={preview} alt="preview" />
Enter fullscreen mode Exit fullscreen mode

This is extremely useful for:

  • image previews
  • profile picture uploads
  • drag-and-drop previews

🕵️‍♂️ Validating Uploaded Files Before Upload

Validation should happen before sending data to the server.

Check file size

if (file.size > 5 * 1024 * 1024) {
  alert("File too large (Max 5MB)");
}
Enter fullscreen mode Exit fullscreen mode

Check file type

if (!file.type.startsWith("image/")) {
  alert("Only images are allowed");
}
Enter fullscreen mode Exit fullscreen mode

These checks help avoid:

  • unnecessarily uploading huge files
  • security risks from unknown MIME types

🖱️ Drag & Drop File Uploading

To support drag-and-drop, we use:

  • onDragOver → prevent default so the file can be dropped
  • onDrop → capture the file

Example:

const handleDrop = (e) => {
  e.preventDefault();
  const file = e.dataTransfer.files[0];
  console.log(file);
};
Enter fullscreen mode Exit fullscreen mode

Drag + drop makes the UI feel modern and user-friendly.


📊 Upload Progress (Simulated or Real)

You can show upload progress using libraries or advanced APIs.
For example, Axios provides an onUploadProgress callback.

This allows implementing a progress bar that updates while the file uploads.


🔄 When to Use JSON vs FormData for File Uploads

When sending regular text inputs, JSON works perfectly:

await fetch("/api/register", {
  method: "POST",
  body: JSON.stringify({ name, email, password }),
});
Enter fullscreen mode Exit fullscreen mode

But JSON cannot handle binary files like images, PDFs, videos, etc.
That’s why we use FormData when files are involved.

Uploading Using FormData

const handleSubmit = async () => {
  const formData = new FormData();
  formData.append("name", name);
  formData.append("email", email);
  formData.append("profileImage", file);

  await fetch("/api/register", {
    method: "POST",
    body: formData,
  });
};
Enter fullscreen mode Exit fullscreen mode

Simple summary:

  • Text-only data → JSON is enough
  • Files involved → use FormData
  • FormData lets you send:

    • text
    • files
    • mixed form fields

This is how most real-world file upload systems work.


📝 Final Thoughts

File uploading is straightforward when using React. It simplifies the process, giving developers enhanced control and flexibility in managing file uploads with JavaScript. By harnessing the power of React, developers can efficiently and effectively handle this functionality.

Key takeaways:

  • File inputs behave the same in HTML and React
  • URL.createObjectURL is amazing for previews
  • Always validate files before upload
  • Use FormData when files are part of your request
  • Drag-and-drop and progress bars are great UX enhancers

Happy coding!

Top comments (0)