Categories
JavaScript Answers

How to compose multipart/form-data with a different Content-Type on each part with JavaScript?

Spread the love

Sometimes, we want to compose multipart/form-data with a different Content-Type on each part with JavaScript.

In this article, we’ll look at how to compose multipart/form-data with a different Content-Type on each part with JavaScript.

How to compose multipart/form-data with a different Content-Type on each part with JavaScript?

To compose multipart/form-data with a different Content-Type on each part with JavaScript, we call the form data append method with a blob.

For instance, we write

const formData = new FormData();

formData.append(
  "items",
  new Blob(
    [
      JSON.stringify({
        name: "Book",
        quantity: "12",
      }),
    ],
    {
      type: "application/json",
    }
  )
);

to call formData.append with the key and a blob.

In the blob, we have the JSON content as a string in an array.

And we set the MIME type of the content by setting type to "application/json".

Conclusion

To compose multipart/form-data with a different Content-Type on each part with JavaScript, we call the form data append method with a blob.

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 *