17

I'm "Reactifying" a file input and can't manage to iterate over selected files.

private onInputChanged = (e: React.FormEvent<HTMLInputElement>): void => {
  let files: FileList | null =  e.currentTarget.files;
  files.map( file => console.log("Do something with " + file.name));
}
<input 
    type="file"
    onChange={this.onInputChanged}
/>

Here is a barebone example of my problem. FileList cannot be used with .map(... and neither .forEach(...

How can I accomplish an iteration on selected files?

Error: Property 'map' does not exist on type 'FileList'

3 Answers 3

33

FileList is an Array like object, that has the length property, and indexed values, but it lacks the Array methods, such as map. With ES6 you can use spread or Array#from to convert it to a real array. In ES5 you can call Array#slice to convert to an array, or call the method on the FileList.

Note: If Array#from causes the TypeScript | Array.from | error TS2339: Property 'from' does not exist on type 'ArrayConstructor' error, change the default target (es3) to ES6 - "target": "ES6" - in the compiler options of the "tsconfig.json", or use the --target ES6 in the command line.

Array.from demo:

const onInputChanged = (e) => {
  const files =  e.currentTarget.files;
  
  Array.from(files).forEach(file => console.log("Do something with " + file.name));
}
<input 
    type="file"
    onChange="onInputChanged(event)"
/>

Calling forEach demo:

const onInputChanged = (e) => {
  const files =  e.currentTarget.files;
  
  [].forEach.call(files, file => console.log("Do something with " + file.name));
}
<input 
    type="file"
    onChange="onInputChanged(event)"
/>

Sign up to request clarification or add additional context in comments.

1 Comment

For what it's worth, Array.slice() did not work for me, but Array.from() did
2

The FileList interface is accessed using the index:

for (let i = 0; i < files.length; i++) {
    console.log(files[i].name);
    //or
    console.log(files.item(i).name);
}

You can use either the index with [0] or via item(0).

2 Comments

Is there any reason someone would use .item(i)? I realize you've probably just mentioned it for completeness but I figured I would ask.
Just there for completeness... although I just spotted a typo on the other line, whoops.
0

You can iterate FileList just:

for (let file of files) {
    console.log("Do something with " + file.name)
}

1 Comment

This was my first instinct but it throws an error for me - "Error TS2495 (TS) Type 'FileList' is not an array type or a string type."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.