如何通过输入文件数组进行映射? [英] How to map through an array of input files?
问题描述
我有两个功能:一个将文件转换为dataUrl,另一个返回结果的承诺:
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返回:TypeError: target.files.map is not a function
.高
target.files.map returns: TypeError: target.files.map is not a function
. H
如何修改getDataUrls
,使其返回带有dataUrls的数组?
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
不是Array
,并且不继承自Array
,但是它确实实现了可迭代协议,因此您可以使用传播语法使其作为数组.
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.
如果您想知道如何检查像FileList
这样的类是否支持扩展语法,则可以执行以下操作:
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.
这篇关于如何通过输入文件数组进行映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!