Home > Web Front-end > JS Tutorial > How Can I Read a Local Text File into a Web Browser Reliably?

How Can I Read a Local Text File into a Web Browser Reliably?

Patricia Arquette
Release: 2024-12-21 01:26:10
Original
375 people have browsed it

How Can I Read a Local Text File into a Web Browser Reliably?

Reading a Local Text File into the Browser

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();
}
Copy after login

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));
Copy after login

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");
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template