Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
The FormData
object is used to hold form values in a key-value pairs data structure.
You create an empty FormData
object in this way:
const fd = new FormData()
Once you have the item you can call one of its methods:
append()
to add a value to the object, with the specified key. If the key already exists, the value is added to that key, without eliminating the first onedelete()
deletes a key value pairentries()
gives an Iterator object you can loop to list the key value pairs hostedget()
get the value associated with a key. If more than one value was appended, it returns the first onegetAll()
get all the values associated with a keyhas()
returns true if there’s a keykeys()
gives an Iterator object you can loop to list the keys hostedset()
to add a value to the object, with the specified key. If the key already exists, the value is replacedvalues()
gives an Iterator object you can loop to list the values hosted
The FormData object is part of the XMLHttpRequest 2 spec. It’s available in all the modern browsers but keep in mind that IE versions prior to 10 do not support it.
Here is one example of using FormData to send the content of a file using an XHR connection:
<input type="file" id="fileUpload" />
const sendFile = file => {
const uri = '/saveImage'
const xhr = new XMLHttpRequest()
const fd = new FormData()
xhr.open('POST', uri, true)
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
const imageName = xhr.responseText
//do what you want with the image name returned
//e.g update the interface
}
}
fd.append('myFile', file)
xhr.send(fd)
}
const handleImageUpload = event => {
const files = event.target.files
sendFile(files[0])
}
document.querySelector('#fileUpload').addEventListener('change', event => {
handleImageUpload(event)
})
This snippet instead can be used to send multiple files:
<input type="file" id="fileUpload" multiple />
const sendFiles = files => {
const uri = '/saveImage'
const xhr = new XMLHttpRequest()
const fd = new FormData()
xhr.open('POST', uri, true)
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
const imageName = xhr.responseText
//do what you want with the image name returned
//e.g update the interface
}
}
for (let i = 0; i < files.length; i++) {
fd.append(files[i].name, files[i])
}
xhr.send(fd)
}
const handleImageUpload = event => {
sendFiles(event.target.files)
}
document.querySelector('#fileUpload').addEventListener('change', event => {
handleImageUpload(event)
})
Download my free JavaScript Beginner's Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More browser tutorials:
- Some useful tricks available in HTML5
- How I made a CMS-based website work offline
- The Complete Guide to Progressive Web Apps
- The Fetch API
- The Push API Guide
- The Channel Messaging API
- Service Workers Tutorial
- The Cache API Guide
- The Notification API Guide
- Dive into IndexedDB
- The Selectors API: querySelector and querySelectorAll
- Efficiently load JavaScript with defer and async
- The Document Object Model (DOM)
- The Web Storage API: local storage and session storage
- Learn how HTTP Cookies work
- The History API
- The WebP Image Format
- XMLHttpRequest (XHR)
- An in-depth SVG tutorial
- What are Data URLs
- Roadmap to learn the Web Platform
- CORS, Cross-Origin Resource Sharing
- Web Workers
- The requestAnimationFrame() guide
- What is the Doctype
- Working with the DevTools Console and the Console API
- The Speech Synthesis API
- How to wait for the DOM ready event in plain JavaScript
- How to add a class to a DOM element
- How to loop over DOM elements from querySelectorAll
- How to remove a class from a DOM element
- How to check if a DOM element has a class
- How to change a DOM node value
- How to add a click event to a list of DOM elements returned from querySelectorAll
- WebRTC, the Real Time Web API
- How to get the scroll position of an element in JavaScript
- How to replace a DOM element
- How to only accept images in an input file field
- Why use a preview version of a browser?
- The Blob Object
- The File Object
- The FileReader Object
- The FileList Object
- ArrayBuffer
- ArrayBufferView
- The URL Object
- Typed Arrays
- The DataView Object
- The BroadcastChannel API
- The Streams API
- The FormData Object
- The Navigator Object
- How to use the Geolocation API
- How to use getUserMedia()
- How to use the Drag and Drop API
- How to work with scrolling on Web Pages
- Handling forms in JavaScript
- Keyboard events
- Mouse events
- Touch events
- How to remove all children from a DOM element
- How to create an HTML attribute using vanilla Javascript
- How to check if a checkbox is checked using JavaScript?
- How to copy to the clipboard using JavaScript
- How to disable a button using JavaScript
- How to make a page editable in the browser
- How to get query string values in JavaScript with URLSearchParams
- How to remove all CSS from a page at once
- How to use insertAdjacentHTML
- Safari, warn before quitting
- How to add an image to the DOM using JavaScript
- How to reset a form
- How to use Google Fonts