2016-09-14 167 views
0

所以我有文件的FileList,我需要将它们全部读取到一个数组即ie。 [fileData1, fileData2],以便我可以将所有文件发送到我的后端。我坚持所有的异步操作,我不知道如何等待事情完成。我需要一种方法来检测何时可以向后端发出请求。我也希望以编程的功能性方式做到这一点。对不起,如果问题不清楚。用FileReader读取多个文件并获取文件列表

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 

回答

1

既然你添加的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); 
+0

cur_file计数器有点打破功能编程的永恒法则。除此之外,如何将文件提取到加载函数之外,而不使用全局变量。 – user2933157

+0

@ user2933157你对'cur_file'说得对,它不是全局变量的原因,我改变了我的代码。至于第二个问题,您可以将一个数组作为参数添加到'read_files'并在那里累积数据。 – redneb

+0

谢谢!当我有机会测试它时,我会在明天尝试。 – user2933157