将参数传递给FileReader onload事件 [英] Pass a parameter to FileReader onload event
问题描述
我需要阅读一些由用户提供的csv文件。使用拖放div将文件传递给页面/脚本,处理文件放置如下:
I need to read some csv files, given by the user. Files are passed to the page/script using a drag and drop div, that handles the file drop as follows:
function handleFileDrop(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
...
}
我需要用csv解析每个文件库,它将其转换为一个数组,但我也需要跟踪我目前解析的文件名。下面是我用来解析每个文件的代码:
I need to parse each file with a csv library that converts it into an array, but I also need to keep track of the file name I'm currently parsing. Here's the code I use to parse each file:
for(var x = 0; x < files.length; x++){
var currFile = files[x];
var fileName = currFile.name;
var reader = new FileReader();
reader.onload = (function(theFile){
return function(e){
var csvArr = CSV.csvToArray( e.target.result, ";", true );
console.log(csvArr);
};
})(currFile);
reader.readAsText(currFile);
}
在此之前,一切都很好。我需要的是将文件名传递给 reader.onload
事件,例如:
Until this, everything works great. What I need is to also pass the filename to the reader.onload
event, eg:
reader.onload = (function(theFile){
return function(e){
***** I need to have fileName value HERE *****
};
})(currFile);
有可能吗?我怎样才能做到这一点?感谢您的任何帮助,最好的问候
Is possible? How can I do this? Thanks in advance for any help, best regards
推荐答案
请尝试以下操作:
Try the following:
var reader = new FileReader();
reader.onload = (function(theFile){
var fileName = theFile.name;
return function(e){
console.log(fileName);
console.log(e.target.result);
};
})(currFile);
reader.readAsText(currFile);
在这里,您要创建一个新的 fileName
每次将文件传递给外部方法时都会变量。然后创建一个访问该变量的函数(由于关闭)并返回它。
Here, you're creating a new fileName
variable each time a file is passed to the outer method. You're then creating a function which has access that variable (due to the closure) and returning it.
这篇关于将参数传递给FileReader onload事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!