FileList
An object of this type is returned by the files
property of the HTML <input>
element; this lets you access the list of files selected with the <input type="file">
element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer
object for details on this usage.
All <input>
element nodes have a files
attribute of type FileList
on them which allows access to the items in this list. For example, if the HTML includes the following file input:
<input id="fileItem" type="file">
The following line of code fetches the first file in the node's file list as a File
object:
const file = document.getElementById('fileItem').files[0];
Properties
length
Read only-
A read-only value indicating the number of files in the list.
Methods
Example
Logging filenames
In this example, we log the names of all the files selected by the user.
HTML
<!--'multiple' is set to allow multiple files to be selected-->
<input id="myfiles" multiple type="file">
<div class="output"></div>
CSS
.output {
overflow: scroll;
margin: 1rem 0;
height: 200px;
}
JavaScript
const output = document.querySelector('.output');
const myFiles = document.querySelector("#myfiles");
function logFilenames(){
const fileInput = document.querySelector("#myfiles");
const files = fileInput.files;
const fileListLength = files.length;
for (let i = 0; i < fileListLength; i++) {
output.innerText = `${output.innerText}\n${files.item(i).name}`;
}
}
myFiles.addEventListener("change", logFilenames);
Result
Specifications
Specification |
---|
File API # filelist-section |
HTML Standard # dom-input-files-dev |
Browser compatibility
BCD tables only load in the browser