Home >Web Front-end >JS Tutorial >How Can I Read Local Text Files in My Browser?

How Can I Read Local Text Files in My Browser?

DDD
DDDOriginal
2024-12-17 08:35:24200browse

How Can I Read Local Text Files in My Browser?

How to Approach Reading Local Text Files in the Browser

You're facing challenges reading local text files in your browser. To address this, consider the following:

1. Incorporate the Fetch API

Introducing the Fetch API offers a streamlined approach for retrieving data from URLs, replacing the XMLHttpRequest method. Implement it like this:

fetch("myText.txt")
  .then((res) => res.text())
  .then((text) => {
    // Process the "text" content
  })
  .catch((e) => console.error(e));

2. Avoid file:///

Modern browsers strictly restrict direct filesystem access. To bypass this, avoid using file:/// prefixes.

3. Use a Web Server for Local Testing

Instead of relying on file:///, employ a lightweight web server, such as:

  • python -m http.server

This allows you to access your data using standard HTTP URLs, mitigating access limitations.

Original Solution

To handle XMLHttpRequest issues, do the following:

  • Check for status 0 when loading local files.
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);
}
  • Specify file:// in your file path.
readTextFile("file:///C:/your/path/to/file.txt");

The above is the detailed content of How Can I Read Local Text Files in My Browser?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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