Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 File API: How to see the result of readAsText()

When readAsText() function is completed the result is stored in .result

How do I see if the content of the file read are correct in .result?

 fr = new FileReader();  fr.readAsText(file);  var x = fr.result;  console.log(x); //does not display anything on console 

Now how do I display the .result object to verify the the content?

like image 692
user32262 Avatar asked Dec 05 '12 17:12

user32262


People also ask

What does the readAsText () function return?

The readAsText() method is used to read the contents of the specified Blob or File . When the read operation is complete, the readyState is changed to DONE , the loadend event is triggered, and the result property contains the contents of the file as a text string.

What does FileReader return?

The FileReader result property returns the file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.


2 Answers

readAsText is asynchronous, so you would need to use the onload callback to see the result.

Try something like this,

var fr = new FileReader(); fr.onload = function(e) {     // e.target.result should contain the text }; fr.readAsText(file); 

Further information here,

https://developer.mozilla.org/en-US/docs/DOM/FileReader

like image 126
lostsource Avatar answered Sep 21 '22 09:09

lostsource


This took me like 300 hours to figure out even after reading the documentation and examples online...

Here's some actual, working code:

let fileReader = new FileReader(); fileReader.onload = function(event) {     alert(fileReader.result); }; inputElement.onchange = function(event) {     fileReader.readAsText(event.target.files[0]); }; 

Also, FYI:

FileReader.onabort A handler for the abort event. This event is triggered each time the reading operation is aborted.

FileReader.onerror A handler for the error event. This event is triggered each time the reading operation encounter an error.

FileReader.onload A handler for the load event. This event is triggered each time the reading operation is successfully completed.

like image 23
Andrew Avatar answered Sep 23 '22 09:09

Andrew