I’m trying to write a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.
function readTextFile() {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "testing.txt", true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
var allText = rawFile.responseText;
document.getElementById("textSection").innerHTML = allText;
}
}
rawFile.send();
}
What is going wrong here?
This still doesn’t seem to work after changing the code a little bit from a previous revision and now it’s giving me an XMLHttpRequest
exception 101.
I’ve tested this on Firefox and it works, but in Google Chrome it just won’t work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)?
You need to check for status 0 (as when loading files locally with
XMLHttpRequest
, you don't get a status returned because it's not from aWebserver
)And specify
file://
in your filename:Local AJAX calls in Chrome are not supported due to same-origin-policy.
If you check console logs you will find "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https."
What this basically means that chrome creates a sort of virtual disk for every domain and access to files outside it are restricted by the listed methods for security reasons. AJAX is basically http, therefore wont work for local files.
Firefox does not put any such restriction therefore your code will work happily in firefox. However there is workaround for chrome too : see here.
Jon Perryman,
Yes js can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html
<input type=file>
.Then with js it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.
What js cannot do for security reasons is to access automatically (without the user input) to the filesystem of his computer.
To allow js to acccess to the local fs automatically is needed to create not an html file with js inside it but an hta document.
An hta file can contain js or vbs inside it.
But the hta executable will work on windows systems only.
This is standard browser behavior.
Also google chrome worked at the fs api, more infos here: http://www.html5rocks.com/en/tutorials/file/filesystem/
Provably you already try it, type "false" as follows: