React Answers

How to post image with fetch and JavaScript?

Spread the love

To post image with fetch and JavaScript, we call fetch with the body set to the form data object with the file to upload.

For instance, we write

const fileInput = document.querySelector("#your-file-input");
const formData = new FormData();

formData.append("file", fileInput.files[0]);

const options = {
  method: "POST",
  body: formData,

fetch("your-upload-url", options);

to select the file input with querySelector.

Then we create a FormData instance and put the selected file there with append.

fileInput.files[0] has the first selected file.

Then we call fetch with the upload URL and options, which has body set to formData.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *