天天看点

前端处理 input 元素的 files 属性时报错【m.map is not a function】

问题描述

在使用 HTML 的文件上传元素

<input type="file">

时,处理其返回的

files

数据时遇到了这个报错

m.map is not a function

我的代码如下:

const uploadCSVFiles = event.target.files;
uploadCSVFiles.map((f) => {
        if (f) {
          setUploadText(`正在上传${f.name}`);
          // 省略
        }
}
           

输出 event.target.files,得到:

前端处理 input 元素的 files 属性时报错【m.map is not a function】

从图片上可以看出这是一个

FileList

类型的数据。

解决方式

经过查阅资料后才发现,这个

FileList

类型虽然看起来是个数组,但其实并不是数组,所以不能使用

map

方法。

map

方法的全称是

Array.prototype.map()

,属于数组类型的方法。

因此我改为使用

for (const ... of ... )

的方式去遍历

FileList

类型,如下:

for (const f of event.target.files) {
      setUploadVis(true);
      if (f) {
        setUploadText(`正在上传 ${f.name} ...`);
        // 省略
      }
}