How to post a file from a form with Axios
Add the file to a formData
object, and set the Content-Type
header to multipart/form-data
.
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
file upload using axios in react
To upload file with axios you need to use FormData:
const formData = new FormData();
// ...
formData.append("data", values.attachedFile[0]);
axios.post(app.resourceServerUrl + '/file/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
Send file with form-data and axios
The solution to my problem was to set Content-Length accordingly:
"Content-Length": fs.statSync(filePath)['size']
axios post request to send form data
You can post axios data by using FormData() like:
var bodyFormData = new FormData();
And then add the fields to the form you want to send:
bodyFormData.append('userName', 'Fred');
If you are uploading images, you may want to use .append
bodyFormData.append('image', imageFile);
And then you can use axios post method (You can amend it accordingly)
axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Related GitHub issue:
Can't get a .post with 'Content-Type': 'multipart/form-data' to work @ axios/axios
Axios POST request sending nothing with 'multipart/form-data' [React Native - Expo]
So after diving through search results in Google, I've found this StackOverflow post: react native post form data with object and file in it using axios
I took the answer provided by user_2738046 in my code and it worked! Combining with Ali's suggestion here is the final code that worked.
const FormData = global.FormData;
const formData = new FormData();
formData.append("userId", user.userId);
formData.append("location", location);
formData.append("description", description);
images.forEach(img => {
const trimmedURI = (Platform.OS === "android") ? img.uri : img.uri.replace("file://", "");
const fileName = trimmedURI.split("/").pop();
const media = {
name: fileName,
height: img.height,
width: img.width,
type: mime.getType(trimmedURI),
uri: trimmedURI
};
formData.append("report-images", media);
});
const response = await axios({
method: "POST",
url: `http://${<my-ip-address>}:3003/api/report/submit`,
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
},
transformRequest: (data, error) => {
return formData;
}
});
// If success, clear all text fields
if (response) {
showToast(7005);
setLocation("");
setImages([]);
setDescription("");
}
setShowLoading(false);
Problem with uploading file through form-data axios
Thanks for everyone, but i found the answer in Postman.Code -> NodeJs - Axios
var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');
var data = new FormData();
data.append('file', fs.createReadStream('/Users/anton/Downloads/50 (1).jpg'));
var config = {
method: 'post',
url: 'https://...',
headers: {
'Authorization': 'Bearer ...',
'Content-Type': 'multipart/form-data',
...data.getHeaders()
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Related Topics
How to Pass Parameters Rendered from Backend to Angular2 Bootstrap Method
Angularjs: How to Pass Variables Between Controllers
CSS Transitions Do Not Work When Assigned Trough JavaScript
How to Dynamically Modify <Select> in Materialize CSS Framework
How to Refresh the Screen on Browser Resize
Full Height of a HTML Element (Div) Including Border, Padding and Margin
How to Build & Deploy a Samsung Smarttv App Without the Ide (E.G: on Linux)
JavaScript Es6 Promise for Loop
Prevent Browser Caching of Ajax Call Result
Is the JavaScript Date Object Always One Day Off
How to Provide Named Parameters in a Function Call in JavaScript
Prevent Address-Bar Hiding in Mobile Browsers
Using Jquery to Know When @Font-Face Fonts Are Loaded