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


ReactJS is a frontend library, so we can use it to create web pages. It’s natural to show data in real-time applications, and the backend manages it. So, whenever React needs data to show on the web page, it gets it from the backend by making API calls.

Sometimes, we may require to send data to the backend to store it in the database. For example, we have taken the user’s profile image and need to send it to the backend to store it in the database.

In many cases, we require to send single or multiple files to the backend using ReactJs. For example, some plagiarism checker tools allow the uploading multiple files to check for plagiarism in the content.

This tutorial will use the axios to send single or multiple files to the backend in ReactJs.

Steps to create the application and send multiple files

Here, we will create two applications. One is React application which we will use for the frontend part, and another is a Node application which we will use as a backend.

Creating the React application

  • Step 1 – Use the below command to create a react app in the project directory.

npx create-react-app app-name

In the above command, the app-name is the name of the app, which users can replace with any name.

  • Step 2 – Now, use the below command and install the axios NPM package in the React application.

npm i axios 
  • Step 3 – Create a file input that can handle multiple files. Also, create a submit button, and when the user clicks it, it should call a function that makes the post request to the backend with multiple files.

  • Step 4 – Create a uploadMultipleFiles() function, which can make post requests using axios.

uploadMultipleFiles() {
   axios({
      url: "http://localhost:8080/addFiles", 
      method: "POST",
      data: { allFiles: files }, 
   })
}

In the above code, users can observe that we have used the endpoints of the backend and “POST” as a value of the method to make a post request to the backend. Furthermore, we have passed the data object while making the request, which we can receive in the backend and manipulate the files.

  • Step 5 – Next, users can add the below code to the App.js file of the application.

import React from "react"; import axios from "axios"; class App extends React.Component { state = { allFiles: [], }; changeFileInput(event) { // using the setState method to set uploaded files to allFiles in the state object let files = event.target.files; this.setState({ allFiles: files }); } uploadMultipleFiles() { // get files from the state let uploadedFiles = this.state.allFiles; let files = []; // get the name of the files and push them to the files array //users can also get files content, convert it to blob format and send it to the backend for (let the file of uploadedFiles) { files.push({ name: file.name }); } axios({ url: "http://localhost:8080/addFiles", // URL to make request method: "POST", // post method to send data data: { allFiles: files }, // attaching the files }) .then((res) => { // handle response console.log(res); }) .catch((err) => { // handle errors console.error(err); }); } render() { return ( <div> <h2> {" "} Using the <i> axios </i> to upload multiple files on NodeJs server.{" "} </h2> <input Type = "file" multiple // adding multiple attributes to allow users to upload multiple files. onChange = {(event) => this.changeFileInput(event)} /> <button onClick = {() => this.uploadMultipleFiles()}> Send Multiple Files to the server </button> </div> ); } } export default App;

In the above code, we have created the file input. Whenever the user uploads multiple files, we call the changeFileInput() function, which sets all files in the allFiles variable of the state object.

When a user clicks the button, it invokes the uplaodMultipleFiles() function, which accesses all files from the state and makes the array of file objects. However, we have only added the file name in the object, but users can access the file content, convert it into the blob object, and add it to the file object.

After that, we used the axios to make post requests to the backend and passed the object as a data value.

  • Step 6 – As a final step, users need to run the application using the below command.

npm start

Creating the Node application

  • Step 1 – Enter the below command in the terminal to create a node application.

node init -y
  • Step 2 – Now, install the required dependencies in the node project. Users should enter the below command in the terminal to install dependencies in the application.

npm i express cors body-parser

We will use express to create a server, cors as a middleware, allowing us to send post requests from frontend to backend. The body-parse will parse the data we have passed while making the post request from the frontend.

  • Step 3 – In the node application, set up the server using the code below.

var express = require("express");
var app = express();
app.listen(8080, function () {
   console.log("server started successfully");
});
  • Step 4 – Now, handle the post request on the ‘/addFiles’ route. In the callback function, get the files from the body using the below code.

app.post("/addFiles", function (req, res) {
   // get files from the body here
});
  • Step 5 – Users can add below full code to the server.js file. If the server.js file doesn’t exist in the project, users can create one file with the server.js name.

// Importing the required and installed modules var express = require("express"); var cors = require("cors"); var app = express(); const bodyParser = require("body-parser"); // using middleware with app app.use(cors()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // allow users to make a post request. app.post("/addFiles", function (req, res) { let allFiles = req.body; console.log(allFiles); }); // Allowing the app to listen on port 8080 app.listen(8080, function () { console.log("server started successfully"); });

In the above code, we have imported the required libraries. After that, we set up the express server in the node application. Also, we have used the body-parse to extract the data from the body and cors as a middleware in the express application.

After that, we created the endpoint which handles the files and prints all the files in the console.

  • Step 6 – We are ready to handle post requests on the node application. Users need to run the node application by running the below command on the terminal.

node server.js

Output

Now, users have both applications running on a different ports. Users can see the output of react application in the image below.

When we upload multiple files on the webpage, the node application prints all file names in the console, as shown in the image below.

We learned to send multiple files to the backend using the axios post request. However, we have sent only file names in this tutorial, but users can also send the file content and updated date, etc.

Updated on: 27-Feb-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements