To read a local text file into the browser, developers traditionally used XMLHttpRequest. One way to do this is through a function that takes the file's path and converts each line of text into a character array:
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(); }
However, this approach often fails with exceptions in browsers other than Firefox. To resolve this, developers should use the Fetch API introduced in JS 2015:
fetch("myText.txt") .then((res) => res.text()) .then((text) => { // do something with "text" }) .catch((e) => console.error(e));
Additionally, it is crucial to avoid using file:/// for security reasons. Instead, consider using lightweight webservers like Python's http.server or HTTP-Server for data loading.
Another issue arises when trying to read files locally using XMLHttpRequest. To address this, developers should check for status 0 since no status is returned for local file loading:
function readTextFile(file) { var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); rawFile.onreadystatechange = function () { if(rawFile.readyState === 4) { if(rawFile.status === 200 || rawFile.status == 0) { var allText = rawFile.responseText; console.log(allText); } } } rawFile.send(null); } readTextFile("file:///C:/your/path/to/file.txt");
The above is the detailed content of How Can I Read a Local Text File into a Web Browser Reliably?. For more information, please follow other related articles on the PHP Chinese website!