2

I am using FileReader in my web app to read a user-selected local file, and when I readAsText() the readyState should change to '2' once completed. Here is the code I have:

        var fr = new FileReader(); // readyState is 0
        var filetoload = $("#foo")[0].files[0];
        fr.readAsText(filetoload); // readyState should be 2!!
        var xml = fr.result; 
        localStorage.setItem('foo', xml);

Now in Firefox, this all works fine and the xml gets written to the localStorage just fine. If I do this Chrome in the console at a resting state (assuming there is a file specified in the #foo input) then it works as well. BUT if I run this normally from the script tag in my .jsp file, readyState = 1 (!) after line 3 above. AND, if I put a breakpoint on line 3, then try to readAsText() from the console, it sets readyState = 1 as well.

What does Chrome need to fully read the file during execution? What am I doing wrong? The fact that it works in Firefox and Chrome only during a resting state in the console leads me to believe there is something more that Chrome needs to allow this or something. Any insight is appreciated, thanks.

Atom999
  • 432
  • 5
  • 17

1 Answers1

1

I was able to find an answer from this post. Since reading the file happens asynchronously, I guess I needed to handle accordingly. Below is what worked for me. (jsonCall() is just an internal function we have that basically calls $.ajax) I hope this helps someone in the future.

    $(document).ready(function(){
        $('#foo').on('click', function(e){
            readFile($("[name='filelocation']")[0].files[0], function(e) {
                // use e.target.result in callback...
                var data = { "xml" : e.target.result };
                jsonCall("myservlet", data, function() {
                    window.open(url, "_blank", "height=800,width=1200");
                })
            });
        });
    });

    function readFile(file, onLoadCallback)
        {
        var fr = new FileReader();
        fr.onload = onLoadCallback;
        fr.readAsText(file);
        }
Atom999
  • 432
  • 5
  • 17