When you have an HTML Form with an <input type="file" />
element, when one or more files are uploaded by the user you will interact with a FileList
object.
如果您HTML表单带有<input type="file" />
元素,则当用户上传一个或多个文件时,您将与FileList
对象进行交互。
That’s not the only place that can give you a FileList
object. You will get one also when interacting with Drag and Drop.
那不是唯一可以给您FileList
对象的地方。 与拖放互动时,您还将获得一个。
Sticking to forms, the input type by default does not allow multiple files to be uploaded.
坚持表格,默认情况下,输入类型不允许上传多个文件。
You will retrieve a FileList with just one element, and you can retrieve it using this syntax:
您将仅使用一个元素来检索FileList,并且可以使用以下语法来检索它:
<input type="file" />
const input = document.querySelector('input')
input.addEventListener('change', e => {
const fileList = input.files
const theFile = fileList[0]
})
Selecting any element from a FileList
object will get a File
object. In this case we just have one, so we select the item at position 0.
从FileList
对象中选择任何元素都会得到一个File
对象。 在这种情况下,我们只有一个,因此我们选择位置0处的项目。
You can also retrieve it using the item()
method, specifying the index:
您还可以使用item()
方法检索它,并指定索引:
const input = document.querySelector('input')
input.addEventListener('change', e => {
const fileList = input.files
const theFile = fileList.item(0)
})
If multiple is enabled though, using the multiple
attribute (<input type="file" multiple />
), FileList will contain multiple elements.
如果启用了multiple
,则使用multiple
属性( <input type="file" multiple />
),FileList将包含多个元素。
You can get the count by looking at the length
property of FileList
.
您可以通过查看FileList
的length
属性来获得计数。
This example loads the files uploaded and iterates on them to print each file’s name:
本示例加载上载的文件并对其进行迭代以打印每个文件的名称:
<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)
}
})