How to Upload Files With React (2024)

How to Upload Files With React (1)

📣

If you're looking for a simple drop-in file upload component, check out Uppy.

Uploading a single file

To upload a single file in React, you need to set the content-type and content-length headers and provide the file contents as the request body:

import { ChangeEvent, useState } from 'react';function FileUploadSingle() { const [file, setFile] = useState<File>(); const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => { if (e.target.files) { setFile(e.target.files[0]); } }; const handleUploadClick = () => { if (!file) { return; } // 👇 Uploading the file using the fetch API to the server fetch('https://httpbin.org/post', { method: 'POST', body: file, // 👇 Set headers manually for single file upload headers: { 'content-type': file.type, 'content-length': `${file.size}`, // 👈 Headers need to be a string }, }) .then((res) => res.json()) .then((data) => console.log(data)) .catch((err) => console.error(err)); }; return ( <div> <input type="file" onChange={handleFileChange} /> <div>{file && `${file.name} - ${file.type}`}</div> <button onClick={handleUploadClick}>Upload</button> </div> );}export default FileUploadSingle;
  1. First, we add an input element with type="file" attribute.
  2. We can store the selected file in React component state, after receiving it from the onChange event. Since we're only able to select a single file, we can get it from the files array on the input: e.target.files[0].
  3. We can upload the file using the Fetch API. We need to set the set body to the file we received from the input and the headers: content-type to the file type and the content-length to file.size. Note that headers must be string values.

I used a httpbin.org API that accepts file uploads and responds with a copy of the request you send. Here's the result:

How to Upload Files With React (2)

Uploading files usually requires some work on the backend to accept, store, and serve those files upon request. If you'd like to learn that and more, I highly recommend educative.io courses.

Here's one that will help you master full-stack development with React:

How to Upload Files With React (4)

Uploading multiple files

To upload multiple files from input element in React, you need to use the FormData JavaScript API and encode the request as multipart/form-data.

import { ChangeEvent, useState } from 'react';function FileUploadMultiple() { const [fileList, setFileList] = useState<FileList | null>(null); const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => { setFileList(e.target.files); }; const handleUploadClick = () => { if (!fileList) { return; } // 👇 Create new FormData object and append files const data = new FormData(); files.forEach((file, i) => { data.append(`file-${i}`, file, file.name); }); // 👇 Uploading the files using the fetch API to the server fetch('https://httpbin.org/post', { method: 'POST', body: data, }) .then((res) => res.json()) .then((data) => console.log(data)) .catch((err) => console.error(err)); }; // 👇 files is not an array, but it's iterable, spread to get an array of files const files = fileList ? [...fileList] : []; return ( <div> <input type="file" onChange={handleFileChange} multiple /> <ul> {files.map((file, i) => ( <li key={i}> {file.name} - {file.type} </li> ))} </ul> <button onClick={handleUploadClick}>Upload</button> </div> );}export default FileUploadMultiple;

The first difference from our single file upload example is the addition of multiple attribute on the input element.

Instead of storing a single file in the React component state, we save the whole FileList in state

📣

Note that the FileList is not an array, so we can't use regular array methods like map or forEach. However, we can still access the members by index fileList[0], loop through the files using for..of or spread them.

To upload multiple files:

  1. Create a FormData object: const data = new FormData();
  2. Append each file you want to upload using FormData.append() - it accepts a form field name, the file, and a file name as parameters.
  3. Using the Fetch API, upload the files by setting form data as body. Note that when you use form data you don't need to set headers manually. It's taken care of by fetch API.

Here's what it looks like:

How to Upload Files With React (5)

Customizing the file input

The default input element doesn't offer much in terms of styling it. To create a custom file upload input in React, you will need to hide the native file upload input and trigger the click events on the input using refs:

import { ChangeEvent, useRef, useState } from 'react';function CustomFileInput() { const [file, setFile] = useState<File>(); const inputRef = useRef<HTMLInputElement | null>(null); const handleUploadClick = () => { // 👇 We redirect the click event onto the hidden input element inputRef.current?.click(); }; const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => { if (!e.target.files) { return; } setFile(e.target.files[0]); // 🚩 do the file upload here normally... }; return ( <div> <div>Upload a file:</div> {/* 👇 Our custom button to select and upload a file */} <button onClick={handleUploadClick}> {file ? `${file.name}` : 'Click to select'} </button> {/* 👇 Notice the `display: hidden` on the input */} <input type="file" ref={inputRef} onChange={handleFileChange} style={{ display: 'none' }} /> </div> );}

Only the input element with file type can open the files for selection in the browser. To upload a file when clicking the custom button, we need to trigger the click() event on the input: inputRef.current?.click();

If we don't want to show the native input, we can hide it by adding the display: none CSS property in it's style attribute or by applying a CSS class that sets the display property to none (e.g. in Tailwind, the class name is hidden).

From then on, you can save the selected files in state or upload them immediately. You now have full customization of the file upload input:

How to Upload Files With React (6)

Conclusion

In React file upload is implemented by using the HTML input element and some JavaScript to make a POST/PUT request to the server with the FormData that contains the selected files.

Your server will then need to process multipart form data to accept file uploads. You can use Multer in Node.js to implement that or upload the files directly to Amazon S3 if that's what you want.

You can find the code used in the examples in my GitHub repo.

Now that you know how to handle files on the front end you should also learn to handle them on the backend, I recommend this full-stack course on educative.io to help you do that:

Building Full-Stack Web Applications With Node.js and React - Learn Interactively

Node.js is a popular JavaScript runtime environment used to create server-side applications. It is an ideal tool for building robust, full-stack web applications with React. This course is an introduction to web development leveraging these two popular technologies. You’ll learn server-side applica…

How to Upload Files With React (7)Educative: Interactive Courses for Software Developers

How to Upload Files With React (8)

On this page

How to Upload Files With React (2024)

FAQs

How to upload files using React? ›

Approach for File Uploading in React JS:
  1. Select a File (user input): To enable the user to pick a file, the first step is to add the tag to our App component. ...
  2. Send a request to the server: After storing the selected file (in the state), we are now required to send it to a server.
Nov 20, 2023

How to upload a PDF file in React? ›

To upload a PDF file in React, you can create a file input element and handle the file upload in React component using state. Then, you can send the selected file to your server or API for processing, or you can display the PDF in the browser by using a third-party library like react-pdf.

How do I import a local file into React? ›

You can follow these steps to import local images to a React component and loop through them:
  1. Create an images folder and put your images inside this folder.
  2. Import each image file into your component file using import statements. You can define each imported image as a variable.

How do I upload a file to react JS hooks? ›

Approach to build drag and drop File Upload Component:
  1. Utilize drop features with HTML5 drag and drop events.
  2. Manage file selection and upload by leveraging the FileReader API along, with AJAX requests.
  3. Show previews of files using the File API. Incorporate design elements and visual cues to improve user interaction.
Mar 11, 2024

How to implement drag and drop file upload in React? ›

To create the DragNDrop component and its associated CSS file, navigate to your project folder and create two new files called DragNDrop. jsx and drag-drop. css. Keep in mind that this article assumes you already have a ReactJS project set up, so we will not go over how to create a new project.

How do I upload multiple files in React? ›

Let's see how we can upload multiple files in React by using a mix of FormData() interface and the Fetch API. The whole magic of the example happens in packFiles() , where we use the FormData. append() method to wrap all the files into one single entity that is sent via a fetch request.

How to upload a PDF file using JavaScript? ›

First, create an index.html with simple input element with a file type attribute:
  1. <input type="file">
  2. <form method="post" enctype="multipart/form-data"> <input name="file" type="file" multiple> <button type="submit">Upload</button> </form>
Aug 2, 2023

How to upload an image file in React JS? ›

Table of contents
  1. Setup a ReactJS app with Vite and TailwindCSS.
  2. Complete the uploader structure.
  3. Handling the file chooser.
  4. Customizing the uploader with reference(useRef)
  5. Handling the file change event.
  6. Previewing the uploaded image from the browser cache.
  7. Uploading the image to the server.
  8. A couple of tasks for you!
Mar 8, 2024

What is the file upload component in React? ›

With the React Upload component, you can enable users to drag and drop files from their file systems to a dedicated user interface by using the drag-and-drop tool or by creating custom elements with a drag-and-drop functionality.

Can React access local files? ›

Accessing files and folders in a React file browser can be done by creating a function that reads the file system and returns the files and folders. This function can then be used in the componentDidMount method or the useEffect hook to read the files and folders when the component is mounted.

How do I import files from public folder in React? ›

Approach to use files in public folder

To access and use files in the public folder in React we can use . env (environment) to store the url of the required file. Then this URL can be used in components/JS files present in the src folder. This grants access to the use of files in the public folder as needed.

How to load a local JSON file in React? ›

Here's how you can do it:
  1. Make sure your datas. json file is located in the public directory or is accessible through the web server. ...
  2. Use fetch with the correct path to the JSON file. If the file is in the public folder, you can reference it with a path relative to the public directory.

How do I import a PNG file into react JS? ›

import React from 'react'; const MyComponent = () => { const imagePath = './path_to_your_image. png'; return ( <div> <img src={require(\ "./yourimage. png")} alt="My Image" /> </div> ); }; export default MyComponent; In the above code, the require() function is used to import the image file.

How to show the file upload progress in React? ›

The React File Upload component displays a built-in progress bar (progress indicator) with the progress percentage during each file upload. The bar is completely customizable.

How to upload a file in React Typescript? ›

log("Uploading file..."); const formData = new FormData(); formData. append("file", file); try { // You can write the URL of your server or any other endpoint used for file upload const result = await fetch("https://httpbin.org/post", { method: "POST", body: formData, }); const data = await result.

How to upload a file with Axios? ›

Uploading Files with Axios: A Step-by-Step Guide

const formData = new FormData(); Adding Files to the FormData Object: Next, you'll need to append the file(s) you want to upload to the FormData object. You can do this using the append method.

Top Articles
Spinal Abnormalities Rarely Cause Back Problems
Why am I getting a
jazmen00 x & jazmen00 mega| Discover
Moon Stone Pokemon Heart Gold
Wordscapes Level 6030
Did 9Anime Rebrand
Optimal Perks Rs3
Xrarse
Youtube Combe
Brenna Percy Reddit
Turbocharged Cars
Things To Do In Atlanta Tomorrow Night
Scholarships | New Mexico State University
The Shoppes At Zion Directory
Kitty Piggy Ssbbw
Accident On The 210 Freeway Today
Busted Mcpherson Newspaper
2021 Volleyball Roster
Craigslist Maryland Trucks - By Owner
Chamberlain College of Nursing | Tuition & Acceptance Rates 2024
Ltg Speech Copy Paste
Cars & Trucks - By Owner near Kissimmee, FL - craigslist
Dexter Gomovies
Ultra Ball Pixelmon
Tottenham Blog Aggregator
San Jac Email Log In
Craig Woolard Net Worth
The Wichita Beacon from Wichita, Kansas
Glossytightsglamour
Trebuchet Gizmo Answer Key
Montrose Colorado Sheriff's Department
Crystal Mcbooty
AI-Powered Free Online Flashcards for Studying | Kahoot!
Natashas Bedroom - Slave Commands
Electronic Music Duo Daft Punk Announces Split After Nearly 3 Decades
Vocabulary Workshop Level B Unit 13 Choosing The Right Word
Anhedönia Last Name Origin
Great Clips Virginia Center Commons
Lucifer Morningstar Wiki
Grizzly Expiration Date Chart 2023
Walmart 24 Hrs Pharmacy
22 Golden Rules for Fitness Beginners – Barnes Corner Fitness
Zeeks Pizza Calories
Dobratz Hantge Funeral Chapel Obituaries
1990 cold case: Who killed Cheryl Henry and Andy Atkinson on Lovers Lane in west Houston?
Is Chanel West Coast Pregnant Due Date
Cryptoquote Solver For Today
Is Chanel West Coast Pregnant Due Date
Grace Charis Shagmag
Lux Nails & Spa
Salem witch trials - Hysteria, Accusations, Executions
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 6566

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.