I have two functions: one that turn files into dataUrl and another that returns a promise with the result:
fileToDataURL(file) {
var reader = new FileReader()
return new Promise(function (resolve, reject) {
reader.onload = function (event) {
resolve(event.target.result)
}
reader.readAsDataURL(file)
})
}
getDataURLs (target) {
// target => <input type="file" id="file">
return Promise.all(target.files.map(fileToDataURL))
}
target.files.map returns: TypeError: target.files.map is not a function
. H
How to modify getDataUrls
so it returns an array with the dataUrls?
function getDataURLs(target) {
// target => <input type="file" id="file">
return Promise.all([...target.files].map(fileToDataURL))
}
FileList
is not an Array
, and does not inherit from Array
, but it does implement the iterable protocol, so you can use the spread syntax to get it as an array.
In case you're wondering how to check if a class like FileList
supports the spread syntax, you can do this:
console.log(FileList.prototype[Symbol.iterator]);
If that returns a function (which it does), then that returned function is a generator function that is invoked on an instance of the class by the spread syntax.
While Patrick Roberts' answer is true, you may face an issue on TypeScript:
Type 'FileList' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. ts(2569)
You can find a complete answer about --downlevelIteration
the post Why downlevelIteration
is not on by default?.
In our case, to iterate on a FileList
, instead of the spread operator, use Array.from()
:
function getDataURLs(target) {
// target => <input type="file" id="file">
return Promise.all(Array.from(target.files).map(fileToDataURL))
}
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