Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch - Missing boundary in multipart/form-data POST

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,

  1. how do I make fetch behave exactly like XMLHttpRequest in this situation?

  2. if this is not possible, why?

Thanks everybody! This community is more or less the reason I have professional success.

like image 437
James Avatar asked Sep 01 '16 20:09

James


People also ask

How do you give a boundary in multipart form data?

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.

How send multipart form data using Fetch?

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 }); // ... }

What is boundary in multipart request?

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.

What is WebKitFormBoundary?

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.


1 Answers

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.

like image 154
James Avatar answered Sep 28 '22 09:09

James