所以我有文件的 FileList,我需要将它们全部读取到一个数组中,即。 [fileData1, fileData2]
,以便我可以向后端发出所有文件的请求。我被所有的异步操作困扰,并且不知道如何等待事情完成。我需要一种方法来检测何时可以向后端发出请求。我还想以函数式编程方式实现这一点。如果问题不清楚,抱歉。
files.map((file) => {
const fr = new FileReader();
fr.readAsDataURL(file)
fr.addEventListener('load', (event) => {
// This is what I need to get to an array
const fileData = event.target.value.substr(fr.result.indexOf(',') + 1);
})
})
//Here I need to make a single post request with all the files in it
最佳答案
既然您添加了功能编程
标签,那么一个好的老式递归函数怎么样:
function read_files(cur_file) {
if (cur_file < files.length) {
// read the next file
const fr = new FileReader();
fr.readAsDataURL(files[cur_file]);
fr.addEventListener('load', (event) => {
// extract the file data from event here
read_files(cur_file+1);
}
}
else {
// we've read all the files
// send the request
}
}
read_files(0);
关于javascript - 使用 FileReader 读取多个文件并获取文件数据数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39492217/