FormData Explained + Ajax, Angular 7, Ionic 4 and React Examples

In this post, we'll learn about the FormData interface available in modern web browsers as a part of the HTML5 spec.

We'll see examples of using FormData with Ajax, Angular 7, Ionic and React.

What's FormData

FormData is simply a data structure that can be used to store key-value pairs. Just like its name suggests it's designed for holding forms data i.e you can use it with JavaScript to build an object that corresponds to an HTML form. It's mostly useful when you need to send form data to RESTful API endpoints, for example to upload single or multiple files using the XMLHttpRequest interface, the fetch() API or Axios.

You can create a FormData object by instantiating the FormData interface using the new operator as follows:

const formData = new FormData()

The formData reference refers to an instance of FormData. You can call many methods on the object to add and work with pairs of data. Each pair has a key and value.

These are the available methods on FormData objects:

  • append() : used to append a key-value pair to the object. If the key already exists, the value is appended to the original value for that key,
  • delete(): used to deletes a key-value pair,
  • entries(): returns an Iterator object that you can use to loop through the list the key value pairs in the object,
  • get(): used to return the value for a key. If multiple values are appended, it returns the first value,
  • getAll(): used to return all the values for a specified key,
  • has(): used to check if there’s a key,
  • keys(): returns an Iterator object which you can use to list the available keys in the object,
  • set(): used to add a value to the object, with the specified key. This is going to relace the value if a key already exists,
  • values(): returns an Iterator object for the values of the FormData object.

File Upload Example with Vanilla JavaScript

Let's now see a simple example of file upload using vanilla JavaScript, XMLHttpRequest and FormData.

Navigate to your working folder and create and index.html file with the following content:

<!DOCTYPE html>
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div id="app"></div>

    <script src="index.js">
    </script>
</body>

</html>

We simply create an HTML document with a <div> identified by the app ID. Next, we include the index.js file using a <script> tag.

Next, create the index.js file and add following code:

document.getElementById("app").innerHTML = `
<h1>File Upload & FormData Example</h1>
<div>
<input type="file" id="fileInput" />
</div>
`;

const fileInput = document.querySelector("#fileInput");

const uploadFile = file => {
  console.log("Uploading file...");
  const API_ENDPOINT = "https://file.io";
  const request = new XMLHttpRequest();
  const formData = new FormData();

  request.open("POST", API_ENDPOINT, true);
  request.onreadystatechange = () => {
    if (request.readyState === 4 && request.status === 200) {
      console.log(request.responseText);
    }
  };
  formData.append("file", file);
  request.send(formData);
};

fileInput.addEventListener("change", event => {
  const files = event.target.files;
  uploadFile(files[0]);
});

We first insert an <input type="file" id="fileInput" /> element in our HTML page. This will be used to select the file that we'll be uploading.

Next, we query for the file input element using the querySelector() method.

Next, we define the uploadFile() method in which we first declare an API_ENDPOINT variable that holds the address of our file uploading endpoint. Next, we create an XMLHttpRequest request and an empty FormData object.

We use the append method of FormData to append the file, passed as a parameter to the uploadFile() method, to the file key. This will create a key-value pair with file as a key and the content of the passed file as a value.

Next, we send the request using the send() method of XMLHttpRequest and we pass in the FormData object as an argument.

After defining the uploadFile() method, we listen for the change event on the <input> element and we call the uploadFile() method with the selected file as an argument. The file is accessed from event.target.files array.

You can experiment with this example from this code sandbox:

Uploading Multiple Files

You can easily modify the code above to support multiple file uploading.

First, you need to add the multiple property to the <input> element:

<input type="file" id="fileInput" multiple />

Now, you'll be able to select multiple files from your drive.

Next, change the uploadFile() method to accept an array of files as an argument and simply loop through the array and append the files to the FormData object:

const uploadFile = (files) => {
  console.log("Uploading file...");
  const API_ENDPOINT = "https://file.io";
  const request = new XMLHttpRequest();
  const formData = new FormData();

  request.open("POST", API_ENDPOINT, true);
  request.onreadystatechange = () => {
    if (request.readyState === 4 && request.status === 200) {
      console.log(request.responseText);
    }
  };

  for (let i = 0; i < files.length; i++) {
    formData.append(files[i].name, files[i])
  }
  request.send(formData);
};

Finally, call the method with an array of files as argument:

fileInput.addEventListener("change", event => {
  const files = event.target.files;
  uploadFile(files);
});

Next, you can check out these advanced tutorials for how to use FormData with Angular, Ionic and React:

About the Author

Techiediaries is a website dedicated to bring you tutorials for the latest web technologies


comments powered by Disqus
DMCA.com Protection Status