Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a local text file?

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)?

like image 276
Danny Avatar asked Jan 21 '13 20:01

Danny


People also ask

How do I read a .TXT file?

How to open a TXT file. You can open a TXT file with any text editor and most popular web browsers. In Windows, you can open a TXT file with Microsoft Notepad or Microsoft WordPad, both of which come included with Windows.

Can browser read local file?

Web browsers (and JavaScript) can only access local files with user permission. To standardize the file access from the browser, the W3C published the HTML5 File API in 2014. It defines how to access and upload local files with file objects in web applications.

How do I view a text file in a browser?

Keep in mind, however, that you will not be able to edit your TEXT file in a web browser. In Chrome and Firefox, you can simply drag and drop your file into a browser window to open it. In Microsoft Edge, you must copy and paste your file's location into Edge's address bar to open the file.


1 Answers

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 a Webserver)

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;                 alert(allText);             }         }     }     rawFile.send(null); } 

And specify file:// in your filename:

readTextFile("file:///C:/your/path/to/file.txt"); 
like image 139
Majid Laissi Avatar answered Sep 21 '22 20:09

Majid Laissi