简体   繁体   中英

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.

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:

<input type="file" id="selectedFile" accept=".txt" />

it fires the onchange event as below

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. however i am unable to get the fr.result to be stored into global variable and use it later on in my code. 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

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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