Categories
JavaScript Answers

How to POST with multipart form data using fetch and JavaScript?

Spread the love

Sometimes, we want to POST with multipart form data using fetch and JavaScript.

In this article, we’ll look at how to POST with multipart form data using fetch and JavaScript.

How to POST with multipart form data using fetch and JavaScript?

To POST with multipart form data using fetch and JavaScript, we can send a FormData object as its body.

For instance, we write

const sendData = async (url, data) => {
  const formData = new FormData();

  for (const [key, value] of Object.entries(data)) {
    formData.append(key, value);
  }

  const response = await fetch(url, {
    method: "POST",
    body: formData,
  });

  // ...
};

to create the senData function.

In it, we create a FormData object.

And then we use the for-of loop with Object.entries to loop through the keys and values of each property in data and add them to the formData object with append.

Then we call fetch to make a post request to the url with body set to formData.

Conclusion

To POST with multipart form data using fetch and JavaScript, we can send a FormData object as its body.

By John Au-Yeung

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

One reply on “How to POST with multipart form data using fetch and JavaScript?”

Hi, I just want to thank you for this article, was searching for this from last 1 month but could not do anything. It was so easy, Thanks a lot.

Leave a Reply

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