Languages
[Edit]
EN

React - multiple files input

3 points
Created by:
Dirask JS Member
3430

In this article, we would like to show you how to upload multiple files in React.

multiple files input

There are two main approaches how to let user to select multiple files:

  • using┬ámultiple property with input element that allows to select in many files per one input,
  • using multiple input elements that each one input let's┬áuser to select only one file.

In this article we want to show how to use second option.

The below example uses multiple <input type="file" /> elements that helps us to select files from a computer and upload them with fetch() method that uses FormData class object to wrap files like classic form element submit action does, but here we send it via AJAX / XHR request. It is verry important to give for each input element proper name to be able to distinct it on the server - below example uses file1, file2 and file3.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const formStyle = {
  padding: 5,
  margin: 10,
  border: '1px solid #c7c7c7',
  borderRadius: 3,
  width: 300
}

const submitStyle = {
  margin: '0 5px 5px auto',
  padding: '7px 10px',
  border: '1px solid rgb(239, 255, 255)',
  borderRadius: 3,
  background: 'rgb(48, 133, 214)',
  fontSize: 15,
  color: 'white',
  display: 'flex',
  cursor: 'pointer'
}

const labelStyle = {
  padding: 10,
  border: 10
}

const Form = () => {
  const handleSubmit = (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    fetch("/example/upload", {
      method: "POST",
      body: formData,
    })
      .then(response => response.text()) // or response.json()
      .then(responseText => {            // with responseData
        console.log(responseText);
      })
      .catch(error => {
        console.error("File upload error!");
      });
  };
  return (
    <form onSubmit={handleSubmit} style={formStyle}>
      <label htmlFor="userfile" style={labelStyle}>Upload file:</label><br />
      <br />
      <input type="file" name="file1" /><br />
      <input type="file" name="file2" /><br />
      <input type="file" name="file3" /><br />
      <br />
      <input style={submitStyle} type="submit" value="Submit!" />

    </form>
  );
};

const root = document.querySelector("#root");
ReactDOM.render(<Form />, root);

Important:

  • each file must be given a name,
  • the number of occurrences of the <input type = "file" /> element indicates the number of files that we send to send to the server.

ReactJS

React - multiple files input
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join