Muneem Habib
Muneem Habib

Reputation: 1094

Failed to read file through FileReader

Following is my snippet of code whcih reads file from client machine and it is working fine.

document.getElementById('files').onchange = function(e) { // Retrieve the file list from the input element //uploadFiles(e.target.files);

Files =e.target.files;
   var reader = new FileReader();

            reader.onload = function (e)
            {
                alert("File loaded successfully");
 }reader.readAsText(e.target.files[0]); 

i am getting File loaded alert successfully. but when i copy this file object in json encoded format and then get this file object thorug json decode then it is not reading file.

My code for encoding and decoding and then reading file is as follows:

indexArray="{'"LayerName":'"'+e.target.files[0]+'"}'

 var obj=JSON.parse(indexArray);

                        Files=obj.RGN;

                       if(obj.RGN)
                       {

                        var reader = new FileReader();
                        reader.onload = function (e)
                        {
                            alert("FIle loaded successfully");
                            var output=e.target.result;
                            console.log("output-----------------------------: "+output);

                        }

                        reader.readAsText(File);   

                       }
                       else
                       {
                           alert("Failed to load file");
                       }   

Now it is not working i am even not getting FAILED TO LOAD FILE. so where i am doing wrong i have just encoded the file object and then decode and read that object?

Upvotes: 1

Views: 1817

Answers (1)

Ali Asif
Ali Asif

Reputation: 37

Since obj.RGN is not a file object. And Reader.readastext works only on file object (asynchronously). You should equal Files to e.target.files then it will work properly.

i.e

reader.onload = function (e) {

}

Files=e.target.files;
reader.readAsText(Files); 

Upvotes: 1

Related Questions