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:
- 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:
Step 3: Install axios module using the following command:
npm install axios
Step 4: Start the server using the following command:
Project structure: Here is the directory structure of the project:
Code for the 2nd approach:
Before clicking 'Send Files' Button:
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:
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.