我试图弄清楚如何在React JS中循环多个文件上传。
最终我希望能够遍历每个文件,以便我可以判断是否只上传了PNG,JPG和MP3文件。我还希望将PNG / JPG文件限制为5MB,将MP3文件限制为2MB。
到目前为止,我无法弄清楚为什么我可以访问一个文件而不是文件数组。
<input id="file" type="file" onChange={this.handleChange.bind(this)} required multiple />
我的handleChange函数看起来像这样:
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
this.setState({
[id]: value
});
console.log(id)
console.log(value)
}
当我选择多个文件时,我只会看到一个文件。例如,上面的两个控制台行产生以下内容:
file
C:\fakepath\My Secret Document.docx
为什么value
中只存储一个值?如何正确遍历每个文件以检查其大小和类型?我对使用JQuery不感兴趣。
答案 0 :(得分:8)
文件包含在event.target.files
内的FileList中,你可以Array.from(event.target.files)
获得一个包含所有文件的数组。
有关FileList
的更多信息