sending api request in axios with files
Sending API Request in Axios with Files
If you are working on a project that requires sending files to a server through an API, Axios is a great JavaScript library to use. In this article, we will discuss how to send an API request in Axios with files.
Send File with FormData
The easiest way to send a file with Axios is by using FormData. In this approach, you create a new FormData object, append the file to it, and then send the request using Axios.
const formData = new FormData();
formData.append('file', file);
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.error(error);
});
In the above code, we create a new instance of FormData and append the selected file to it. Then we use Axios to send a post request to the server at the URL '/api/upload'. We pass in the FormData object as the second argument and set the headers to 'multipart/form-data' to tell the server that we are sending a file.
Send Multiple Files with FormData
To send multiple files with Axios, you can simply append each file to the FormData object using a loop.
const formData = new FormData();
files.forEach(file => {
formData.append('files[]', file);
});
axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.error(error);
});
In the above code, we loop through each file in the 'files' array and append them to the FormData object using the 'append' method. Then we send the request using Axios as before.
Send File as Base64 String
You can also send a file as a base64 string using Axios. This approach does not require the use of FormData and is useful when you need to send the file as part of a JSON object.
// Read the file as a base64 string
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const base64File = reader.result;
// Send the file as JSON
axios.post('/api/upload', {
file: base64File
}).then(response => {
console.log(response.data);
}).catch(error => {
console.error(error);
});
};
In the above code, we use the FileReader API to read the selected file as a base64 string. Then we send the file as part of a JSON object using Axios.