Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
When the user selects files with an <input type="file" />, you get a FileList. You also get a FileList from the Drag and Drop API.
Without the multiple attribute, the user can select only one file, so the FileList has one item. Example:
<input type="file" />
const input = document.querySelector('input')
input.addEventListener('change', (e) => {
const fileList = input.files
const theFile = fileList[0]
})
Accessing an item in a FileList returns a File object. Use index 0 for the first file. You can also use the item(index) method:
const input = document.querySelector('input')
input.addEventListener('change', (e) => {
const fileList = input.files
const theFile = fileList.item(0)
})
With the multiple attribute (<input type="file" multiple />), the user can select multiple files. Use the length property to get the count.
Example: iterate over the selected files and show each file name:
<input type="file" multiple />
const input = document.querySelector('input')
input.addEventListener('change', (e) => {
const files = input.files
const filesCount = files.length
for (let i = 0; i < files.length; i++) {
const file = files[i]
alert(file.name)
}
})