Skip to content Skip to sidebar Skip to footer

Javascript Filereader Onload ( Get File From Server )

What I want is to read a file from the windows file system or a server so I can display the contents on the website and we are not allowed to use a database or PHP only Javascript.

Solution 1:

I got it to work


 var file = readTextFile("test.txt");
 var allText;
 var trumpCount = 0;
 var hilaryCount = 0;
 var reader = newFileReader();
// Entire fileconsole.log(this.result);
 // alert(allText);// By linesvar lines = allText.split('\n');
for(var line = 0; line < lines.length; line++){
 // alert(lines[line]);if (lines[line].indexOf("t") !== -1){
    trumpCount++;
  }else{
  hilaryCount++;
  }

}
alert("Votes for trump: " + trumpCount +  " Votes for hilary: " + hilaryCount + " Total votes: " + (trumpCount + hilaryCount))

functionreadTextFile(file)
{
var rawFile = newXMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
    if(rawFile.readyState === 4)
    {
        if(rawFile.status === 200 || rawFile.status == 0)
        {
           allText = rawFile.responseText;
            //alert(allText);
        }
    }
}
rawFile.send(null);
}

Solution 2:

You are not allowed to do this due to security reasons.

File objects may be obtained from a FileList object returned as a result of a user selecting files using the input element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement.

https://developer.mozilla.org/nl/docs/Web/API/FileReader

Post a Comment for "Javascript Filereader Onload ( Get File From Server )"