Languages

How to get or set boundary in multipart/form-data from FormData?

5 points
Asked by:
Zayaan-Rasmussen
543

As in topic: I would like to set up my own boundary parameter for Content-Type when I work with FormData class in JavaScript.

Expected header:

Content-Type: multipart/form-data; boundary=------some-random-characters

My source code looks in the folowing way:

const requestData = new FormData();
requestData.append('file', file); // file from File API

const response = await fetch('/backend/upload', {
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/form-data; boundary=------some-random-characters',
        'Accept': 'application/json'
    },
    body: requestData
});
var responseData = await response.json();

When I execute the source code, header Content-Type is correct, but in body I have:

------WebKitFormBoundary2lZSUsxEA3X5jpYD instead of ------some-random-characters.

Request screenshot from Google Chrome DevTools:

Any idea how to get or set boundary for FormData?

1 answer
2 points
Answered by:
Zayaan-Rasmussen
543

At this moment there is no way to set up boundary for FormData.

Just remove: 'Content-Type': 'multipart/form-data; boundary=------some-random-characters' - it will cause the Content-Type will be set according to body type.

Fixed code:

const requestData = new FormData();
requestData.append('file', file); // file from File API

const response = await fetch('/backend/upload', {
    method: 'POST',
    headers: {
        'Accept': 'application/json'
    },
    body: requestData
});
var responseData = await response.json();

See also

  1. JavaScript - send POST JSON fetch() request 
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join