How to use FormData and send multipart-data in the Browser (Web API )?

About

FormData is a web api object that represent the data of a form that should be send if the form is submited.

Formdata Browser Devtool

Therefore if you have a checkbox that is not checked, formdata will not collect it.

You can create/build it and :

As javascript object, you will get a set of key/value pairs representing form fields and their values.

When send, the data is encoded in multipart/form-data encoding 1)

It's part of the XHR specification 2)

Example

How to send a form data

  • via Ajax XHR: You can also just send it via a Xhr request
var request = new XMLHttpRequest();
request.open("POST", "http://example.com/api");
request.send(formData);
let formData = new FormData(form);
fetch("/combo/api/v1.0/publication/subscription", {
     body: formData,
     cache: 'no-cache',
     method: "post",
     mode: 'no-cors',
     redirect: 'follow',
     credentials: 'same-origin'
  })
  .then(response => console.log(response))

Build from the form

<form id="form1" onsubmit="handleSubmit(this); return false;">
<input name="user" type="text" value="Foo" />
<input name="age" type="number" value="10" />
<input name="button" type="submit" value="Let mee see the input data !" />
</form>

The FormData constructor takes a form element as parameter. See FormData constructor Specification

handleSubmit = (form) => {
  // build the formData object
  let formData =  new FormData(form);
  // retrieve the entries in a entries variable of iterator type
  let entries = formData.entries();
  // loop over the iterator
  let result = entries.next();
  while (!result.done) {
    console.log("Input: Name: "+result.value[0]+", value: "+result.value[1]);
    result = entries.next();
  }
}
  • Result:

Management

Create

Manually

let formData = new FormData();
formData.append('username', 'foo');
formData.append('age', '10');
formData.append('tag', 'cool');
formData.append('tag', 'bar');

// You can't get all entries but you can get all values for one key
console.log(formData.getAll("tag").length);

Form

From a form, only successful form controls are included, i.e. those:

let formData =  new FormData(document.getElementById('form1'));

From a key-value object

const formData = new FormData();
Object.keys(data).forEach(key => formData.append(key, data[key]));

Read

As iterator

The entries of a formData return an iterator.

Example:

let formData = new FormData();
formData.append('username', 'foo');
formData.append('age', '10');
// The entries function returns an iterator
let it = formData.entries();
  • The loop (iteration)
let result = it.next();
while (!result.done) {
 console.log(result.value); 
 result = it.next();
}

As an Object

const formJson = Object.fromEntries(formData.entries());

As an array of key-value pair

[...formData.entries()]

Browser Devtool

You can see it nicely formatted in the BrowserDevtool

Formdata Browser Devtool

Event

The formdata event is fired when:

  • a form is constructing the entry list of the form data after the submit event. You could then add data in the list.
  • a new FormData() constructor is created.

Example:

<form id="form1" onSubmit="handleSubmit(this); return false;">
<p><label>FirstName</label> <input name="firstname" type="text" value="FirstNameDefault"/></p>
<p><input name="button" type="submit" value="Let mee see the formDataEvent !" /></p>
</form>
  • The FormData cannot cancel the action of a submit. Therefore, we take over the submit event, prevent it and build ourself the formdata.
let handleSubmit = (form) => {
    console.log('submit event was fired');
    // build the form data to fire the FormDataEvent on the form
    new FormData(form);
}
document.addEventListener("formdata", (formDataEvent) => {
    
    console.log('formdata event was fired');

    // Get the form data from the event object via values
    let formData = formDataEvent.formData;
    console.log("entries:");
    for (var entry of formData ) {
        console.log(entry[0]+" : "+entry[1]);
    }
    console.log("");

    // Get the form data from the event object via get
    console.log("Input is present ? : "+formData.has("firstname"));
    console.log("Value via the name attribute is: "+formData.get("firstname"));
    
    // You can also
    // delete(name) 
    // getAll(name) (for multiple)
    // set(name, value) and set(name, blobValue, filename)
    
    // submit further the data via XHR
    // let request = new XMLHttpRequest();
    // request.open("POST", "/formHandler");
    // request.send(data);
});

Construction Process

The formData is populated by following this procedure: constructing-the-form-data-set

Documentation / Reference

1)
As see in the extracting body procedure where they run the multipart/form-data encoding algorithm, with object’s entry list





Discover More
Chrome Devtool Xhr Fetch Request
Browser - XMLHttpRequest (XHR) API

The XMLHttpRequest is a web api function that performs an resource fetch with an Aysnchronous HTTP request XMLHttpRequestAPIAJAX programmingfetch API The status of an XHR request. Value Constant...
HTML - How to retrieve the data of a form with Javascript

This article shows you how to retrieve the data of a form with Javascript succesful controls You don't need to submit a form to get the values Every form object has a elements property that stores...
Html Radio Illustration
HTML - Radio

A radio represents a serie of mutually-exclusive choices in a form. It is an input element of type radio. A radio is round to distinguish from the square checkbox. As the checkbox, the state...
HTML - multipart/form-data encoding / mime

multipart/form-data is a mime part used in the enctype form attribute to encode the keyword and corresponding state of input field before sending into the body of the HTTP request formdata This encoding...
Form Tabular Data Illustration
How to create a HTML form for tabular data (rows)

This article shows you how to create a HTML form for tabular data (rows)
Html Checkbox Illustration
How to create and use a HTML checkbox ?

This article gives you all the important information about HTML checkbox and how to use them
How to use the Select HTML Element?

select is an HTML control form element used for selecting one or more value amongst a set of options. It creates a drop-down list used in a form that will set a scalar value from a list of options. ...
Html Input File Multiple Warning Dialog
How to work with an Input File in an HTML form?

The input file is an input of type file that permits to select files or directory and send them to the browser file system api HTML HTML The HTML Result from the operating system: This...
Javascript - Iterator

In Javascript, an iterator is an iterator An object has an iterator when it has: a property named Symbol.iterator that return an object that implement the iterator...



Share this page:
Follow us:
Task Runner