Attach Images in HTTP Requests | Intro to Form Data

JSON is the de-factor choice of transmitting data across the internet in the modern day. Its easy-to-read nature is pleasing for both human and computer.

When we are sending API requests we usually use JSON formatted string as our request payload. However, it has its flaws when it comes to sending data, i.e. it can only send data that can be converted into string. Binary data like images, PDF files can’t be sent with JSON.

So how do we resolve this?

The answer is: use FormData .

Form Data is an alternative way in JavaScript to send data in API requests. We can pack almost any type of data in a FormData object, e.g. images, files, blob and etc.

Similar to JSON, FormData is essentially a series of key and value pairs. We use the append method on a FormData instance to add a key value pair. However, when we pack an array into a FormData , we will need to put a pair of square bracket after the key, e.g.

Let’s take a look at the code:

That’s it!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store