Saturday, December 28, 2024
Google search engine
HomeLanguagesHow to send one or more files to an API using axios...

How to send one or more files to an API using axios in ReactJS?

Assuming that you want to send multiple files from the front-end, i.e., the React app, to the server using Axios. For that, there are two approaches as shown below:

  • Send multiple requests while attaching a single file in each request.
  • Send a single request while attaching multiple files in that request itself.

We are going to follow the second approach, and here are a few points to justify the action:

  1. In the first approach, we will have to make extra requests to send multiple files across the server, whereas, in the second approach, we will only have to make one request.
  2. The first approach will lead to the wastage of computing power, and it might add to extra costs if you are using cloud service providers like Google Cloud Platform(GCP) or Amazon Web Services(AWS).
  3. The first approach isn’t easy to handle the back-end server’s files, whereas it is simpler in the second approach.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app multiple_files

Step 2: Move to the directory containing the project using the following:

cd multiple_files

Step 3: Install axios module using the following command:

npm install axios

Step 4: Start the server using the following command:

npm start

Project structure: Here is the directory structure of the project:

Project Structure

Code for the 2nd approach:

Filename: App.js

Javascript




import React from "react";
import axios from "axios";
  
class App extends React.Component {
  state = {
    files: null,
  };
  
  handleFile(e) {
    // Getting the files from the input
    let files = e.target.files;
    this.setState({ files });
  }
  
  handleUpload(e) {
    let files = this.state.files;
  
    let formData = new FormData();
  
    //Adding files to the formdata
    formData.append("image", files);
    formData.append("name", "Name");
  
    axios({
      // Endpoint to send files
      url: "http://localhost:8080/files",
      method: "POST",
      headers: {
        // Add any auth token here
        authorization: "your token comes here",
      },
      // Attaching the form data
      data: formData,
    })
      .then((res) => { }) // Handle the response from backend here
      .catch((err) => { }); // Catch errors if any
  }
  
  render() {
    return (
      <div>
        <h1>Select your files</h1>
        <input
          type="file"
          multiple="multiple"  //To select multiple files
          onChange={(e) => this.handleFile(e)}
        />
        <button onClick={(e) => this.handleUpload(e)}
        >Send Files</button>
      </div>
    );
  }
}
  
export default App;


Output: 

Before clicking 'Send Files' Button:

Browser output with multiple files selected

To chose files click on the Choose Files button and select multiple files. After choosing the required files, click the Send Files button.

After clicking 'Send Files' Button:

Sending a request with the files

You can see in the above photo that the files you have selected have been successfully attached in the form of data while sending to the server. 

Note: You can use appropriate packages in the backend to handle these files and can send the response from the server accordingly.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments