简体   繁体   English

JavaScript - 使用HTML5 FileReader读取文件

[英]JavaScript - Reading file with HTML5 FileReader

I'm currently learning JavaScript and I'm struggling to read a txt file and use its contents in the program, what I have so far: 我正在学习JavaScript,我正在努力阅读txt文件并在程序中使用它的内容,到目前为止我所拥有的:

fileBtn.addEventListener("change", function()
{ 
 var content = [];
 var file = fileBtn.files[0];
 readFile(file, function(data)
 {
   console.log(JSON.parse(data));
   //content.push(JSON.parse(data)) doesn't work, data is undef.
 });

});

and a function readFile 和一个函数readFile

function readFile(file, f)
{
  var reader = new FileReader();
  reader.onload = function(evt)
  {
   f(evt.target.result);
  };
   reader.readAsText(file);
}

My txt file is currenty only containing a "1", and it logs this number to the console but I can't work with it, if I try to push it into an array the values is suddenly undefined. 我的txt文件是currenty只包含一个“1”,它将这个数字记录到控制台,但我无法使用它,如果我试图将它推入一个数组,值突然未定义。 My goal is to use the content of the file in the program later on 我的目标是稍后在程序中使用该文件的内容

1 . 1。 no need to use JSON.parse if the text file only contain string . 如果文本文件只包含字符串,则无需使用JSON.parse。 data is containing all the text file content data包含所有文本文件内容

2 . 2。 you need to put var content = []; 你需要把var content = []; globally and not inside the function readFile 全局而不是函数readFile

follow this snippet of code i think it will solve your problem 按照这段代码,我认为它将解决您的问题


 <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <label for="file-upload" class="custom-file-upload"> Custom Upload </label> <input id="file-upload" type="file" /> <input id="log-content" type="button" value="Click Me"/> </body> <script> var content = []; function readFile(file, f) { var reader = new FileReader(); reader.onload = function (evt) { f(evt.target.result); }; var text = reader.readAsText(file); } var fileBtn = document.getElementById("file-upload"); var logContnt = document.getElementById("log-content"); logContnt.addEventListener("click", function () { alert(content); }) fileBtn.addEventListener("change", function () { var file = fileBtn.files[0]; readFile(file, function (data) { content.push(data); }); }); </script> </html> 

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM