1

How can I use the Web API fetch method to post a file as the request body?

window.fetch('https://www.example.com',
    {
        method: 'POST',
        headers: new Headers({'content-type': 'application/octet-stream'}),
        body: FILE
    }
)
Lee Goddard
  • 10,680
  • 4
  • 46
  • 63

1 Answers1

3

You can do something like this

let input = document.querySelector('input[type="file"]');
let data = new FormData();
data.append('file', input.files[0]);

fetch('https://www.example.com', {
  method: 'POST',
  body: data
});
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54