What is the Fetch API equivalent of XMLHttpRequest.send(file)?
fetch
can take a second argument, init
, which specifies advanced options of the request. In particular, you can specify the method
and the body
options:
fetch(url, { method: 'POST', headers: new Headers({ "Content-Type": "image/jpeg", }), body: file,})
You can also pass the same options to the Request
constructor.
body
must a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Fortunately, File objects are just a special kind of Blobs, and can be used everywhere where Blobs are accepted.
This can be done like this:
var input = document.querySelector('input[type="file"]')var data = new FormData()data.append('file', input.files[0])fetch('/avatars', { method: 'POST', body: data})