javascript - 使用 FileReader 读取多个文件并获取文件数据数组

标签 javascript functional-programming filereader

所以我有文件的 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/

相关文章:

javascript - 仅提交表单中的特定字段

javascript - Ajax 提交多值

java - 当在运行时收到谓词函数的名称时,如何将函数作为谓词传递给另一个函数?

haskell - 在多个属性上编写有序比较的优雅方式

java - 从服务器检索 pdf 文件流

javascript获取元素唯一选择器

如果页面未查看事件页面,JavaScript 计时器不会运行

scala - 如何跟踪不可变设计的依赖关系?

java - 读取带有换行符的csv文件作为数据java

php - 使用php阅读带图片的ms word文档