FileList对象

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.

您可以通过查看FileListlength属性来获得计数。

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)
  }
})

翻译自: https://flaviocopes.com/filelist/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值