I am trying to figure out how to loop through multiple file uploads in React JS.
Ultimately I want to be able to loop through each file so that I can tell if only PNG, JPG, and MP3 files are being uploaded. I also want PNG/JPG files to be restricted to 5MB and MP3 files to be restricted to 2MB.
So far, I cannot figure out why I can access one file rather than an array of files.
<input id="file" type="file" onChange={this.handleChange.bind(this)} required multiple />
My handleChange function looks something like this:
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)
}
When I select more than one file, I only get one showing up. For example, the two console lines above produce the following:
file
C:\fakepath\My Secret Document.docx
Why is only a single value stored in value
? How can I properly loop through each file to check its size and type? I am not interested in using JQuery.
The files are contained in a FileList, inside event.target.files
, you can do Array.from(event.target.files)
and got an array with all the files selected.
More information about FileList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With