How to send one or more files to an API using axios in ReactJS?
Last Updated :
04 Apr, 2023
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:
- 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.
- 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).
- 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 StructureCode 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 selectedTo 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 filesYou 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.
Similar Reads
How to get meta data of files in firebase storage using ReactJS ? Within the domain of web development, effective file management is a frequent necessity, and Firebase Storage emerges as a resilient solution. This article explores the nuances of extracting metadata from files housed in Firebase Storage through the lens of ReactJS. PrerequisitesNode JS or NPMReact
2 min read
How to Make GET call to an API using Axios in JavaScript? Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain JavaScript o
3 min read
How to make POST call to an API using Axios.js in JavaScript ? Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain Javascript o
2 min read
How to Implement File Download in NextJS using an API Route ? In web development, facilitating file downloads is a common requirement, whether it's providing users with documents, images, or other media files. NextJS, with its versatile API routes and server-side capabilities, offers an elegant solution for implementing file downloads. In this article, we'll e
5 min read
How to send Basic Auth with Axios in React & Node ? Basic Auth is a simple authentication scheme. It involves sending a username and password with each request to the server through HTTP. Axios is a popular HTTP client for making requests in JavaScript. In this article, we will create a React App to demonstrate sending basic Auth with Axios and discu
5 min read