使用 FileReader 读取多个文件并获取文件数据数组
Reading multiple files with FileReader and getting array of the filedatas
所以我有文件的 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
既然你添加了 functional-programming
标签,一个好的老式递归函数怎么样:
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);
所以我有文件的 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
既然你添加了 functional-programming
标签,一个好的老式递归函数怎么样:
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);