Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

364
Vistas
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!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda