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 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: