thanks for stopping by.
I want to send a new FormData()
as the body
of a POST
request using the fetch api
the operation looks something like this
var formData = new FormData() formData.append('myfile', file, 'someFileName.csv') fetch('https://api.myapp.com', { method: 'POST', headers: { "Content-Type": "multipart/form-data" }, body: formData } )
the problem here is that the boundary, something like
boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu
never makes it into the Content-Type:
header
it should look like this
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu
when you try the "same" operation with a new XMLHttpRequest()
, like so
var request = new XMLHttpRequest() request.open("POST", "https://api.mything.com") request.withCredentials = true request.send(formData)
the headers are correctly set
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu
so my question is,
how do I make fetch
behave exactly like XMLHttpRequest
in this situation?
if this is not possible, why?
Thanks everybody! This community is more or less the reason I have professional success.
The boundary is included to separate name/value pair in the multipart/form-data . The boundary parameter acts like a marker for each pair of name and value in the multipart/form-data. The boundary parameter is automatically added to the Content-Type in the http (Hyper Text Transfer Protocol) request header.
The basic idea is to use the FormData object (not supported in IE < 10): async function sendData(url, data) { const formData = new FormData(); for(const name in data) { formData. append(name, data[name]); } const response = await fetch(url, { method: 'POST', body: formData }); // ... }
A boundary is just the 'key' to separate the multiple "parts" of a multipart payload. Normally something like '&' is enough to separate the variables but you need something more unique to separate the payloads within the payload.
Each item in a multipart message is separated by a boundary marker. Webkit based browsers put "WebKitFormBoundary" in the name of that boundary. The Network tab of developer tools do not show file data in a multipart message report: They can be too big.
The solution to the problem is to explicitly set Content-Type
to undefined
so that your browser or whatever client you're using can set it and add that boundary value in there for you. Disappointing but true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With