-1

I'm trying to load simple text file in javascript, unfortunately with no success. my code is:

var my_text:any; var my_file:File = new File([], "C:\\Users\\riki7\\Downloads\\classes.txt"); var reader = new FileReader(); reader.onload = function() { my_text = reader.result; }; reader.readAsText(my_file); alert(my_text); 

after this code runs, I would expect to see classes.txt file content in pop-up alert, instead I get 'undefined'. my file contains a, b, c.

does anyone know what is my problem? maybe the first parameter for File() constructor?

2
  • my_text doesn't exist at the point you're trying to alert it. It hasn't loaded yet. Commented Jun 6, 2022 at 10:53
  • I edited my answer please check it it's working. Commented Jun 6, 2022 at 11:01

3 Answers 3

0

You have to use html tag <input type="file" id="input" /> and then hung a event listener on it, like that

const inputElement = document.getElementById("input"); inputElement.addEventListener("change", handleFiles, false); function handleFiles() { const fileList = this.files; /* now you can work with the file list */ } 

then after simply bypass your file into the FileReader

const reader = new FileReader(); reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img); reader.readAsDataURL(file); 

And i guess that would be it. You can find more examples there: https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications

Having your code where your alert runs upfront the callback function. If you need to see alter with the content, simply move your alert into the callback function:

reader.onload = function() { my_text = reader.result; alert(my_text); }; 

because my_text is not ready when you call alert outside.

Sign up to request clarification or add additional context in comments.

Comments

0

<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; test = fr.result; alert(fr.result); } fr.readAsText(this.files[0]); } </script>

3 Comments

I pasted this code and got few errors.
I just create it new.html file and pasted my code it works fine, it seems like you tried code from console or idk, cause when I run it from console with document.write(`code here`) it gave error.
Worked fine when I used it
0

<html> <head> <script> var fileReadEvent = function(event) { var input = event.target; var reader = new FileReader(); reader.onload = function(){ var text = reader.result; alert(text) }; }; </script> </head> <body> <input type='file' accept='text/plain' onchange='fileReadEvent(event)'><br> </body> </html>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.