React upload multiple files (2024)

Let's see how we can upload multiple files in React by using a mix of FormData() interface and the Fetch API.

If you prefer the video format you can checkout the youtube I've made for this tutorial:

In this example, we want to build React app that uploads a few files and shows a busy indicator the files are sent to the server. Below is the final app in action (the HD version is here):

React upload multiple files (2)

And here is the full code for it:

import {useState} from 'react'const API_URL = 'https://httpbin.org/post'const API_METHOD = 'POST'const STATUS_IDLE = 0const STATUS_UPLOADING = 1const App = () => { const [files, setFiles] = useState([]) const [status, setStatus] = useState(STATUS_IDLE) const uploadFiles = (data)=> { setStatus(STATUS_UPLOADING) fetch(API_URL, { method: API_METHOD, body: data, }) .then((res) => res.json()) .then((data) => console.log(data)) .catch((err) => console.error(err)) .finally(() => setStatus(STATUS_IDLE)) } const packFiles = (files)=> { const data = new FormData() [...files].forEach((file, i) => { data.append(`file-${i}`, file, file.name) }) return data } const handleUploadClick = () => { if (files.length) { const data = packFiles(files) uploadFiles(data) } } const renderFileList = () => (<ol> {[...files].map((f, i) => ( <li key={i}>{f.name} - {f.type}</li> ))} </ol>) const getButtonStatusText = () => ( (status === STATUS_IDLE) ? 'Send to server' : <img src = "./load.svg" /> ) return (<div> <input type="file" accept="image/*" multiple onChange={(e)=> setFiles(e.target.files)} /> {renderFileList()} <button onClick={handleUploadClick} disabled={status === STATUS_UPLOADING}> {getButtonStatusText()} </button> </div>)}

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.

If you want to dive more into the FormData interface I've written two articles about it:

We are using the HttpBin service as a dummy endpoint placeholder. After receiving the request it just outputs back a JSON object where we can see the uploaded items in the files property.
React upload multiple files (3)
The file uploader was customized so that it allows the section of multiple files and it takes only images as inputs. You can use the multiple and accept attributes to change these behaviors.
React upload multiple files (4)

The actual files state variable is not an array, but it's iterable, so we can use the spread operator to get an array of files:

const renderFileList = () => (<ol> {[...files].map((f, i) => ( <li key={i}>{f.name} - {f.type}</li> ))}</ol>)

As a final note, you can use the URL.createObjectURL() to make image previews for the uploaded files.

You can see here the GitHub repo for this example, and here is the live working app.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

Leave a Reply

React upload multiple files (2024)

FAQs

How to upload multiple files in ReactJS? ›

append() method to wrap all the files into one single entity that is sent via a fetch request. If you want to dive more into the FormData interface I've written two articles about it: a basic intro for fetch() and FormData. and one that goes more into details about FormData and the append() method.

How to handle multiple file upload in JavaScript? ›

Uploading Multiple Files Using JavaScript
  1. Step 1: Create an HTML form with a file input element that allows Multiple file selections. ...
  2. Step 2: Add an event listener to capture file selection. ...
  3. Step 3: Use FormData to Store Files. ...
  4. Step 4: Send the AJAX request using XMLHttpRequest.
Oct 4, 2023

How do I upload large files to Reactjs? ›

Uploading large files in a React application, using AWS S3 pre-signed URLs, provides a secure and efficient way to handle file transfers. By offloading the actual file transfer to AWS S3, you reduce the load on your server, and by using pre-signed URLs, you maintain a high level of security.

How to upload files in 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 send multiple files in response in node js? ›

Upload multiple files in Node. js (video tutorial)
  1. Upload one image using the Node.js SDK.
  2. Run the code and get a response.
  3. Upload multiple images.
  4. Run the code and get a response.
  5. Install p-limit.
  6. Set the concurrent promise limit.
  7. Batch upload using p-limit.
  8. Run the batch upload.
Mar 31, 2024

How to upload multiple files using one file input element? ›

When present, it specifies that the user is allowed to enter more than one value in the <input> element. Note: The multiple attribute works with the following input types: email, and file. Tip: For <input type="file"> : To select multiple files, hold down the CTRL or SHIFT key while selecting.

How do I upload a large number of files? ›

Best Ways to Share Big Files
  1. Upload your files to a cloud storage service.
  2. Use WeTransfer, a free online service.
  3. Use a VPN.
  4. Use FTP.
  5. Transfer files using SFTP.
  6. Use file compression software, like 7-Zip.
  7. Purchase a USB flash drive.
  8. Use Jumpshare, a free online service.
Apr 19, 2023

How do I load large data in ReactJS? ›

In simpler words, this technique means to only render the list items required to fill in the entire page length, and then add more items as the user scrolls down. We can implement this using the react-infinite-scroller library. Here's the implementation of the same 10,000-item list using react-infinite-scroller.

How to handle big file upload? ›

However, you can upload large files efficiently by:
  1. Storing files directly in the cloud.
  2. Splitting large files into smaller parts or chunks.
  3. Ensuring your files are stored in the nearest storage bucket and take the shortest route to your cloud storage.
Feb 10, 2023

How to upload a csv file in React JS? ›

Importing data from a CSV file into a React. js application is straightforward with the help of the papaparse library. By creating a reusable CsvFileInput component and managing the data state in the parent App component, we can easily handle CSV file uploads and display the imported data.

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 upload multiple images and preview it using ReactJS? ›

To upload image and preview it using React JS we will use the HTML file input for the image input. After taking input the image url is created using URL. createObjectURL() method and store in the useState variable named file. Display the image as preview using the html img tags with the file url in the src prop.

How do I upload multiple files to React Dropzone? ›

React Dropzone can be easily configured to accept multiple file uploads. This is done by setting the multiple prop to true in the getInputProps function. This allows users to select more than one file at a time from the file dialog or to drag and drop multiple files into the dropzone.

How do I import multiple images into React? ›

context method.
  1. First, create a directory to store all your images. For example, let's create a folder named "images" in the src folder.
  2. Place all your images inside the "images" folder.
  3. In your React component file, import the require context method as shown below:

How do I select multiple files in React? ›

The file manager allows you to select multiple files by enabling the allowMultiSelection property (enabled by default). The multiple selection can be done by pressing the Ctrl key or Shift key and selecting the files.

Top Articles
5 Reasons to Ditch Your Debit Card
QA Engineer Education Requirements - Do You Need a Degree?
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated:

Views: 6294

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.