Home >Web Front-end >JS Tutorial >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:
This allows you to access your data using standard HTTP URLs, mitigating access limitations.
Original Solution
To handle XMLHttpRequest issues, do the following:
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 Local Text Files in My Browser?. For more information, please follow other related articles on the PHP Chinese website!