FormData in JavaScript

The most common way of sending data to the server in a network request is by using a JSON object. But, in some cases, JSON maybe insufficient to transmit the data.

Let's see what are these use-cases and how we can handle them in JavaScript.

Fundamentals

Form data can be used instead of JSON to transmit data like binaries to the server. A network request that uses form data looks something like this:

POST /api/submit HTTP/1.1
Host: tinyfrontend.com
Content-Type: multipart/form-data;boundary="random-hash"

--random-hash
Content-Disposition: form-data; name="field1"

value1
--random-hash
Content-Disposition: form-data; name="field2"; filename="example.txt"

...contents of the file...
--random-hash--

Let's break it down to understand what the different parts mean:

  • Content-Type: This is a request header that specifies that it is a form-data request. It's value in this case will always be multipart/form-data, followed by the boundary.

  • Boundary: This is a random hash to define the boundary for the content so that the server can parse the key-value pairs correctly.

  • Content-Disposition: Provides information about each subpart of the form. Starts with form-data, followed by name which is the key to identify the value with. Different parameters are separated by a semicolon(;).

FormData

The request format shown above looks quite complicated, isn't it? Thankfully, JavaScript provides a FormData API that makes it as easy as creating a JSON object to create the form-data request payload.

To create a FormData object, simply call the constructor:

const form = new FormData();

Subscribe to read the full content