axios: Can't get a .post with 'Content-Type': 'multipart/form-data' to work
I’ve spent a few hours today trying to get a post request to work with a few parameters and a file that I need to upload.
I was able to make it work with pure javascript and XMLHttpRequest but it doesn’t work with Axios. What am I doing wrong?
Here’s the code that works using XMLHttpRequest:
let data = new FormData();
data.append('action', 'ADD');
data.append('param', 0);
data.append('secondParam', 0);
data.append('file', new Blob([payload], { type: 'text/csv' }));
// this works
let request = new XMLHttpRequest();
request.open('POST', url);
request.send(data);
What would be the ‘Axios’ version of that?
Here’s one of my tries (the simple one):
// this won't work
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
axios.post(url, data, config)
.then(response => console.log(response))
.catch(errors => console.log(errors));
Thank you! And thanks for your great work with Axios!
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 144
- Comments: 99 (9 by maintainers)
Links to this issue
- Не работает метод API shop.product.skus.update — Webasyst
- Дмитрий — Хаб поддержки Webasyst
- reactjs - axios post request to send form data - Stack Overflow
- javascript - How do I set multipart in axios with react? - Stack Overflow
- javascript - How to send data correct axios Error: Multipart: Boundary not found - Stack Overflow
- facebook graph api - Node.js - Axios - Upload file to another server - Stack Overflow
@rafaelbiten I’ve just tried to reproduce the issue but to no avail. I used the following code:
The data was successfully sent to the server:
Two years latter: Same problem…
This is definitely working for me—all browsers, including Safari iOS.
My code is something like this:
function samplePost (config) {
};
// call samplePost to upload
samplePost({
});
From: Antonio Vázquez notifications@github.com Sent: Tuesday, September 11, 2018 11:23 AM To: axios/axios axios@noreply.github.com Cc: DavidRueter drueter@assyst.com; Comment comment@noreply.github.com Subject: Re: [axios/axios] Can’t get a .post with ‘Content-Type’: ‘multipart/form-data’ to work (#318)
4 hours and counting to make a post request from Safari. Still not happening… what the hell guys ??
None of the solutions here worked from me… 😦
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/axios/axios/issues/318#issuecomment-420371510 , or mute the thread https://github.com/notifications/unsubscribe-auth/AFbi6JQBv06LTwL4z3HIAlvXAXDyps1-ks5uZ_9wgaJpZM4Ibm_z . https://github.com/notifications/beacon/AFbi6BSPfwPvNaWPFSdvtLKRYXS1m4uKks5uZ_9wgaJpZM4Ibm_z.gif
just add boundary to
Content-Type
:@demeter-macik thanks, adding boundary worked for me 😄
If anyone is wondering, here’s an example how to use
FormData
withaxios
. You basically have to stream the data into a buffer and pass the correct headers.@krzkaczor Try adding in the content-type if you have not done so already
Please reopen until there is some consistent answer/workflow for this. It seems like a lot of people are still experiencing issues with this.
@nickuraltsev this is a minimal example that doesn’t work on node:
Error: write after end
@Sreekhar Set Content-Type to undefined to let browser change it to multipart/form-data and add boundary automatically
@Sreekhar I don’t know if it will work, but could you maybe add the FormData as the second argument instead of wrapping it in another object?
axios.post('/dataAPI/sendFile', fd, config)
If you need to use ‘UploadCommand’ as the name of the part where the file is, you need to use this
fd.append('UploadCommand', this.refs.multipartfiles.files[0]);
Hi @nickuraltsev , I’m getting the same issue.
Please find the screen shot of my header information below,
I have a question, does axios support sending multi-part data files to node server?
this worked:
axios.post(localhost:3000/items, formData, { headers: { ‘Content-Type’: ‘multipart/form-data’ }});
@guncha Your example worked for me in 0.15.3, until I tried to upload a binary file, which ended up encoded as UTF8. Telling concat to use a buffer fixed the issue.
I tried different solutions but in the end I handled this issue adding the headers:
this worked for me too, thanks @arvi
twiliosms = async (Codigo) => {
var FormData = require(‘form-data’); var fs = require(‘fs’);
var form = new FormData(); form.append(‘To’, ‘+524772773737’); form.append(‘From’, ‘+737373737’); form.append(‘Body’, Codigo);
try { let axapi = await axios( { url: ‘2010-04-01/Accounts/AC8aa53c907943af79234414bb725c2cd3/Messages.json’, baseURL: ‘https://api.twilio.com’, headers: {‘content-type’:
multipart/form-data; boundary=${form._boundary}
,}, data: form, auth: { username: ‘AC8aa53c907943af79234414bb725c2cd3’, password: ***, }, method: ‘post’, } )} catch (e) {console.error(e)} }
+1 reopen
for me , this works:
and this won’t work
be aware of the postdata param format should be
(url , FormData)
, not(url, {data: FormData})
Also when using buffers to represent file, this worked for me:
Hi @Sreekhar For me I changed config to
const config = { headers: { 'Content-Type': 'application/json' } };
and it worked fine@Googrosh Yes. Yes. Yes.
Spent half a day figuring out whether it is related to client or server config. At the end,
headers: form.getHeaders()
did the trick.I’m wandering this library still require self-written workarounds for form data posts…
I agree with @epferrari, please consider reopen this issue. It’s ok to send a base64 string with FormData in chrome, but just can’t get it done with axios in node(v8.9.3). And it works with node-fetch…
=== update === I don’t understand, I use the same headers for node-fetch and axios, and it seems that they post the same form data to server, how come they end up differently? By the way, the real url which I’m posting comes from here, what I’m doing is mock the browser’s http request with nodejs, to send a image to server and get a link back.
This may not be on point, but the issue might be related to using
body-parser
on the server side. I was struggling with a similar issue and ran across this post:https://philna.sh/blog/2016/06/13/the-surprise-multipart-form-data/
TL;DR -
body-parser
doesn’t handle multipart/form-data. In other words,axios
isn’t the problem andbody-parser
is. This might be why the buffer solutions mentioned above work.I assume this functionality is for security reasons, as noted here:
http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html
I hope that helps someone!
Alternatively, I would use a promise:
@PierreCavalet nope, I used
request-promise
instead.To this day, this is not working on nodejs. The
request-promise
approach also worked for me.I got around this by using:
I struggled with this a lot longer that I want to admit, so hopefully this helps someone. I am using axios, express, and express-fileupload. I can successfully upload to Node with params I have appended to the FormData. I pick up the files with req.files and I pick up the rest of the form data with req.body[‘yourfilename’]
Server (Express):
router.post('/helper/amazon/upload', function(req, res) { if (!req.files) { return res.status(400).send('No files were uploaded.') } console.log(req.body.filename); return console.log(req.files);
Front-end (axios)
const formData = new FormData(); formData.append('file', this.validFile); formData.append('filename', 'trails/' + this.$route.params.id.split('-')[0] + '/camping/'); axios.post(
/api/helper/amazon/upload, formData, { headers: { 'Content-Type': 'multipart/form-data' } });
Result:
Important to note: any of the above solutions do NOT work if you have any default data parameters set in the defaults of the Axios instance. You might also check if you specify a default Content-Type header in your Axios instance (via axios.defaults.headers and axios.defaults.parameters).
HTTP posts that include binary file data seem to work fine in axios v0.16.2
@rrapant The issue with duplicate content type values has been fixed by #317. The fix will be included in the next release. Thank you!
Possibly related header issue. When content-type is set in config object in request it is concatenated e.g. axios.post( ‘https://example.com/login’, {emailAddress: email, password: hashedPassword}, {headers: {‘content-type’: ‘application/json’}} );
header content-type comes in as application/json,application/json body will not be parsed in this case
@Googrosh Brilliant,
.getHeaders()
got it working for me too. I can’t tell you how many hours I spent on this. Thanks!Moved to
got
because it just works withformData
andmultipart/form-data
- https://github.com/sindresorhus/got 🙌 Close, but no cigar Axios 👋not working with golang
can we get this reopened? Looks like a lot of people are still bumping up against this, including myself. For example, this request doesn’t make it to the server as expected via axios, but if I send the same file over Postman as
multipart/form-data
, all works.Edit: My problem was trying to send a base64 encoded data-uri as form-data. If anyone else is struggling with the same issue, here is some sample code to convert it:
@krzkaczor thanks, forced to switch too
@nickuraltsev right! What you see on that screenshot is all I have on dev tools. @rrapant may be right, but I’m almost sure that setting
'Content-Type'
or not, at least on this case, wasn’t changing anything. I would have to check again to be sure.check your axios.create, this headers should “headers:{}” and no use data.like this : var instance = axios.create({ headers: { // ‘Content-Type’: ‘application/x-www-form-urlencoded;charset=UTF-8’, }, // data: {}, params: {} });
hii plz i need helps : i got “file: This value should not be blank.” when i try to fetch post an image using fetch :
Code works in browser but not on node.
@krzkaczor Have you found any work around to send multipart/form-data with axios ?
Closing this for now. Please feel free to reopen if necessary.