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?
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With