What is the process for uploading a file using the JavaScript fetch API?

I’m trying to understand file uploading with JavaScript. I have a file input field for users to select files, as shown below:

<form>
  <div>
    <label>Choose a file to upload</label>
    <input type="file">
  </div>
  <button type="submit">Upload</button>
</form>

I can handle the submit event, but I’m uncertain about how to actually send the file with fetch. What should be included in the fetch request?

fetch('/upload', {
  method: 'POST',
  // What should I include in the body? Do I need to set a content-type header?
}).then(response => {/* handle response */});

hey there! you need to use FormData to include the file in your fetch req. like this: new FormData(yourForm). just pass it directly as body in fetch. no need for content-type header, it’ll be set automatically. happy coding! :smile: