FileList object

Find out what a FileList object is and how to use it

When you have<input type="file" />Element, when a user uploads one or more files, you will beFileListpurpose.

That's not the only place that can give you a chanceFileListpurpose. You will also get one when interacting with drag and drop.

Stick to the form. By default, the input type does not allow multiple files to be uploaded.

You will use only one element to retrieve the FileList, and you can use the following syntax to retrieve it:

<input type="file" />
const input = document.querySelector('input')

input.addEventListener(‘change’, e => { const fileList = input.files const theFile = fileList[0] })

Select any element from itFileListObject will get aFile object. In this case we just have one, so we select the item at position 0.

You can also useitem()Method, specify the index:

const input = document.querySelector('input')

input.addEventListener(‘change’, e => { const fileList = input.files const theFile = fileList.item(0) })

If more than one is enabled, usemultipleAttributes(<input type="file" multiple />), FileList will contain multiple elements.

You can checklengththe property ofFileList.

This example loads the uploaded files and iterates through them to print the name of each file:

<input type="file" multiple />
const input = document.querySelector('input')

input.addEventListener(‘change’, e => { const files = input.files const filesCount = fileList.length

for (let i = 0; i < files.length; i++) { const file = files[i] alert(file.name) } })

Download mine for freeJavaScript beginner's manual


More browser tutorials: