JavaScript FormData

The FormData interface in JavaScript offers a mechanism to generate an object composed of key-value pairs. These objects can be transmitted across the web utilizing the fetch function or the XMLHttpRequest.send method. It leverages the capabilities of HTML form elements. The format it employs mirrors that of a form when its encoding type is designated as "multipart/form-data".

Additionally, we can directly supply it to the URLSearchParams constructor, which will extract the query parameters in a manner similar to the behavior observed in the <form> tag during the submission of a GET request.

Typically, it is utilized to construct a data set that can be dispatched to the server. The FormData object functions as an array of arrays, with each individual array representing a specific element.

These arrays have the following three values:

name: It contains the name of the field.

value: This represents the value of the field, which may be either a String or a Blob object.

filename: This parameter includes a string that represents the filename. The name will be stored on the server when a blob object is provided as the second argument.

Why FormData?

HTML form elements are designed to automatically collect their respective fields and values. In these cases, the FormData interface proves to be beneficial as it allows us to transmit HTML forms, whether they include files or extra fields.

It is an entity that holds the information submitted by the user through the form fields.

Below is the form data constructor:

Example

let formData = new FormData([form]);

FormData instances can be utilized as the request body in network methods like fetch. By default, they are encoded and transmitted with the Content-Type set to multipart/form-data.

The server will interpret this as a standard form submission.

Let’s delve into a straightforward illustration of transmitting FormData.

Sending a Basic FormData

In the following form, we are transmitting a straightforward FormData object to the server.

Index.html:

Example

<form id="myform">

  <input type="text" name="name" value="Alex">

  <input type="text" name="surname" value="Smith">

  <input type="submit">

</form>



<script>

  formElem.onsubmit = async (e) => {

    e.preventDefault();

const data=new FormData(myform)

    let response = await fetch('url', {

      method: 'POST',

      body: data

    });



    let result = await response.json();

Console.log(result);

  };

</script>

In the preceding example, we refrain from establishing any backend API for transmitting the data, as this falls outside the parameters of this tutorial. However, we can examine the payload within the network tab to gain insight into the functionality of the FormData interface.

When we examine the network request within the developer tools, we can observe the following payload:

In the network request detailed above, the form data is transmitted over the network utilizing the FormData object. Alternatively, we must define several methods to retrieve the data from the form.

Therefore, by utilizing the FormData interface, we can effortlessly transmit the formData to the server. This can be accomplished with a simple one-liner code.

FormData Constructor

The FormData constructor serves the purpose of generating a new FormData instance. It can be utilized in the subsequent manners:

Example

new FormData()

new FormData(form)

new FormData(form, submitter)

Parameters:

form (Optional):

It is an HTML <form> element; when defined, the FormData object will be filled with the current keys/values from the form. The keys are derived from the name attribute of each element, while the values correspond to what has been submitted. Additionally, it encodes the content from file input elements.

submitter (Optional):

The submit button is a component of a form. When the submit button includes a name attribute property, the corresponding data will be incorporated into the FormData object.

FormData Methods

FormData offers a variety of methods that can be useful for retrieving and altering the data within the form fields.

In certain instances, it may be necessary to modify the form data prior to transmitting it to the server. The following methods can be advantageous for such scenarios.

Following are some useful formData methods:

formData.append(name, value)

This function accepts the name and value of two parameters and subsequently creates a form field object that incorporates the specified name and value.

formData.append(name, blob, fileName)

The function accepts three parameters: name, blob, and fileName. It appends a field to the form data objects if the HTML element corresponds to <input type="file">. Subsequently, the fileName argument specifies the name of the file based on the filename from the user's file system.

formData.delete(name)

This function accepts a name as an input parameter and eliminates the field that corresponds to the provided name.

formData.get(name)

Additionally, it accepts a name as a parameter and retrieves the value of the designated field associated with that name.

formData.has(name)

It additionally accepts the name as an input parameter, verifies whether the field corresponding to the provided name exists, and returns true if it does; if not, it returns false.

A form may contain several fields that share the same name; therefore, it is essential to utilize multiple append methods to include all fields that have identical names.

However, fields that share the same name can lead to errors and complicate their configuration within the database. To address this issue, the formData offers an alternative approach that utilizes the same syntax as the append method. This alternative first eliminates all fields that possess the specified name and subsequently adds a new field. As a result, it guarantees that each key will have a distinct name.

Example

formData.set(name, value)

formData.set(name, blob, fileName)

In the set method, the syntax operates similarly to that of the append method.

How to Iterate FormData?

The FormData interface offers the FormData.entries method, which allows for the iteration over all of its keys. This method yields an iterator that traverses through each key/value pair contained within the FormData object. In this context, a key is represented as a string object, while the corresponding value can be either a blob or a string.

Consider the below example:

Example

formData.append("key1", "value1");

formData.append("key2", "value2");



// Display the key/value pairs

for (const pair of formData.entries()) {

  console.log(`${pair[0]}, ${pair[1]}`);

}

The output of the above example will be:

Example

key1, value1

key2, value2

Sending a form with a file of data

Files may also be transmitted utilizing FormData. This functionality operates with the form element and is transmitted as Content-Type: multipart/form-data. The multipart/form-data encoding facilitates the transfer of files. Consequently, by default, <input type="file"> is included in the form data. Therefore, we can upload files to the server using the form-data encoding.

Consider the below example:

Example

<form id="myform">

  <input type="text" name="firstName" value="Alex">

  File: <input type="file" name="picture" accept="image/*">

  <input type="submit">

</form>



<script>

  myform.onsubmit = async (e) => {

    e.preventDefault();

	const data=new FormData(myform)

	console.log(data)

    let response = await fetch('url', {

      method: 'POST',

      body: data

    });



    let result = await response.json();

  };

</script>

In the preceding illustration, the image object is transmitted in binary format via the FormData. We can observe this in the network section of the developer tools:

Sending form data as a Blob object

Transmitting form data as a blob object provides a straightforward method for sending dynamically created binary data. This can include various types of files, such as images or other blobs. We can seamlessly transfer this data to the server by including it in the body of a fetch request.

Transmitting image data along with various types of form data, including fields like name and password, is quite practical. Additionally, servers tend to handle multipart-encoded forms more efficiently compared to raw binary data.

Examine the following example, which demonstrates how to transmit an image in conjunction with additional form data as part of a form submission.

Example

<body>

  <canvas id="mycanvas" width="200" height="120"></canvas>



  <input type="button" value="Submit" onclick="submit()">



  <script>

    mycanvas.onmousemove = function(e) {

      let ctx = mycanvas.getContext('2d');

      ctx.lineTo(e.clientX, e.clientY);

      ctx.stroke();

    };



    async function submit() {

      let imageBlob = await new Promise(resolve => mycanvas.toBlob(resolve, 'image/png'));



      let formData = new FormData();

      formData.append("firstName", "Alex");

      formData.append("image", imageBlob, "image.png");



      let response = await fetch('url', {

        method: 'POST',

        body: formData

      });

      let result = await response.json();

      alert(result.message);

    }



  </script>

</body>

In the preceding illustration, the inclusion of the image blob is demonstrated in the following manner:

Example

formData.append("image", imageBlob, "image.png");

This is equivalent to an <input type="file" name="image">, where the user has uploaded a file named "image.png" containing a data imageBlob sourced from the file system. The server will process this as standard form data.

Input Required

This code uses input(). Please provide values below: