How to POST with multipart/form-data header and FormData using fetch
If you open up your network inspector, run this code snippet, and submit the form you should see that the Content-Length
is set correctly:
const foo = document.getElementById('foo')foo.addEventListener('submit', (e) => { e.preventDefault() const formData = new FormData(foo) formData.append('userId', 123) fetch('//example.com', { method: 'POST', body: formData })})
<form id="foo"> <input id="file" type="file" name="file"/><br><br> <button type="submit">Submit</button></form>
I hit my head against a similar wall, specifically using isomorphic-fetch
on node to POST a multipart form. The key for me was finding .getHeaders()
. Note that NPM description for form-data
suggests that it'll "just work" without this, but it doesn't seem to, at least not in node (I think browsers inject header stuff?).
// image is a Buffer containing a PNG image// auth is the authorization tokenconst form_data = new FormData();form_data.append("image", png, { filename: `image.png`, contentType: 'application/octet-stream', mimeType: 'application/octet-stream'});const headers = Object.assign({ 'Accept': 'application/json', 'Authorization': auth,}, form_data.getHeaders());try { const image_res = await fetch(url, { method: 'POST', headers: headers, body: form_data }); if (!image_res.ok) { const out = await image_res.json(); console.dir(out); return; }}catch (e) { console.error(`Chart image generation exception: ${e}`);}