[英]Reading multiple files in a loop using HTML5 File API
I am using the HTML5 File API to read binary files. 我使用HTML5文件API来读取二进制文件。 The user can select multiple files and then click a button to copy them into a JavaScript object.
用户可以选择多个文件,然后单击按钮将它们复制到JavaScript对象中。 My code is listed here:
我的代码列在这里:
<script>
var data = new Object;
function ReadFiles()
{
var files = document.getElementById('file').files;
for (var i = 0; i < files.length; i++) {
var reader = new FileReader();
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
data["File_Content" + i] = btoa(evt.target.result);
}
};
reader.readAsBinaryString(files[i]);
}
}
</script>
<input type="file" id="file" name="file[]" multiple />
<button onclick="ReadFiles();">Read Files</button>
If the user puts in three files, then only an invalid property 'File_Content3' will be added to the 'data' object with value; 如果用户输入三个文件,则只有无效的属性“File_Content3”将被添加到具有值的“data”对象中; the other three valid properties 'File_Content0', 'File_Content1' and 'File_Content2' are not created.
不创建其他三个有效属性'File_Content0','File_Content1'和'File_Content2'。
Can anybody solve the problem? 任何人都可以解决这个问题吗? Thanks.
谢谢。
You have a clouse issue with the i
variable, I'd simply use another variable 你有
i
变量的clouse问题,我只是使用另一个变量
var j = 0, k = files.length;
for (var i = 0; i < k; i++) {
var reader = new FileReader();
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
data["File_Content" + j] = btoa(evt.target.result);
j++;
if (j == k){
alert('All files read');
}
}
};
reader.readAsBinaryString(files[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.