How to Use the FormData Object
Discover the functionality of the FormData object and learn how to effectively utilize it.
The FormData object serves as a storage mechanism for preserving input field values within a form. It is particularly beneficial when you need to transmit files to a server. This object is typically only utilized in such circumstances.
To demonstrate the utilization of FormData in sending file content via fetch, consider the following example:
1 | <input type="file" id="fileUpload" /> |
Here, an input field of type “file” is presented. An event listener is attached to the input field, specifically to the “change” event, as shown below:
1 | document.querySelector('#fileUpload').addEventListener('change', event => { |
The majority of the logic is then managed within the handleImageUpload()
function:
1 | const handleImageUpload = event => { |
In this particular example, a POST request is carried out to the /saveImage
endpoint. It is possible to send additional data by appending it to the formData
object. To access the file data on the server-side, it is imperative to parse the request as a multipart form. For more insight on this, refer to the guide on how to upload files in a Next.js form.
The FormData object provides various useful methods, including:
append()
: This method adds a value to the object with a specified key. If the key already exists, the new value appends to the existing one.delete()
: By implementing this method, you can delete a particular key-value pair.entries()
: It returns an Iterator object that allows you to iterate over and list the key-value pairs contained within the object.get()
: When invoked, this method retrieves the value associated with a specified key. If multiple values were appended, it returns the first one.getAll()
: With this method, you can retrieve all values associated with a specific key.has()
: Typically, this method returns a boolean value indicating whether a particular key exists within the object.keys()
: It returns an Iterator object that enables iteration and listing of the keys within the object.set()
: This method adds a value to the object with the specified key. In the case where the key already exists, the existing value gets replaced.values()
: It returns an Iterator object that facilitates iteration and listing of the values within the object.
The FormData object is a component of the XMLHttpRequest 2 specification and is supported by all modern browsers. It is most commonly used for sending images via fetch. For guidance on how to handle server-side image uploads, refer to the guide on how to handle file uploads in Node.js.
tags: [“FormData object”, “file upload”, “fetch”, “multipart form”, “XMLHttpRequest 2”]