[英]How to load file content to variable using FileReader
I would like to seek some help please regarding loading txt file content to variable using input element in javascript.关于使用 javascript 中的输入元素将 txt 文件内容加载到变量中,我想寻求一些帮助。
So i am working with java script file separate from html file, and when the user click on button to load the file from the html side as below:所以我正在使用与 html 文件分开的 java 脚本文件,当用户单击按钮从 html 端加载文件时,如下所示:
<input type="file" id="selectedFile" accept=".txt" />
it fires the onchange event as below它会触发 onchange 事件,如下所示
document.getElementById('selectedFile').addEventListener('change', function () {
var fr = new FileReader();
fr.onload = function () {
document.getElementById('display').textContent = fr.result;
console.log(fr.result);
}
fr.readAsText(this.files[0]);
})
basically if i console log the fr.result as in the code up there, i can see the content with no issues, and also i have div element with id "display" and content gets updated no issues.基本上,如果我在上面的代码中控制台记录 fr.result,我可以看到没有问题的内容,而且我有 id 为“显示”的 div 元素并且内容更新没有问题。 however i am unable to get the fr.result to be stored into global variable and use it later on in my code.但是我无法将 fr.result 存储到全局变量中并稍后在我的代码中使用它。 I tried the below code:我尝试了以下代码:
let test = "";
document.getElementById('selectedFile').addEventListener('change', function () {
var fr = new FileReader();
fr.onload = function () {
document.getElementById('display').textContent = fr.result;
test = fr.result;
}
fr.readAsText(this.files[0]);
})
console.log(test);
but the test variable in console comes out empty and runs even before i choose the file with input element.但是控制台中的测试变量甚至在我选择带有输入元素的文件之前就显示为空并运行。 Any advices about what i missing here, and how i can get the file content using same method to be stored in variable?关于我在这里遗漏的任何建议,以及如何使用相同的方法将文件内容存储在变量中? Thanks!谢谢!
I tried it it works like this, it was maybe because your event listener function was an anonymous function, and you can't call this
in anonymous function我试过它是这样工作的,可能是因为你的事件监听函数是一个匿名函数,你不能在匿名函数中调用this
<input type="file" id="selectedFile">
<p id="display"></p>
<script>
var fr = new FileReader();
let test;
document.getElementById('selectedFile').addEventListener('change', x);
function x() {
fr.onload = ()=>{
document.getElementById('display').innerText = fr.result;
console.log(fr.result);
test = fr.result;
}
fr.readAsText(this.files[0]);
}
console.log(test);</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.