Sending Images via API | 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.

formData.append('recipients[0]', ‘somevalue')

Let’s take a look at the code:

That’s it!

Web Development. https://acadea.io/learn . Follow me on Youtube: https://www.youtube.com/c/acadeaio