0

Overview: I have been looking into ways of reading in a textfile without the need of filereader. I have a file called temp.txt located at "/temp.txt" (absolute path) and I have been using the following javascript function to try to read and print out the text located inside the txt file.

function readTextFile(file){
  alert("Debug 1");
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, true);
  rawFile.onreadystatechange = function ()
  {
      if(rawFile.readyState === 4)
      {
          if(rawFile.status === 200 || rawFile.status == 0)
          {
              var allText = rawFile.responseText;
              alert(allText);
          }
      }
  }
   rawFile.send(null);
   alert("Nothing");
}

I use a button that calls the function onclick like so:

<button onclick="readTextFile('file:///temp.txt')">read the txt</button>

The Problem: When I click the button nothing happens. I have tried putting "file:///temp.txt" directly into my browser and the browser manages to correctly open the text file. Am I implementing the javascript wrong? I have tested this in Chrome. Thank you so much in advance!

Update 1: I have fixed some bugs on my code and have gotten the code to run the alerts, but when its supposed to print out the textfile in the alert(alert(allText);) it prints out nothing.

Sources: Javascript - read local text file

You can try the code here: https://jsbin.com/mucosavage/edit?html,output just change the "/temp.txt" to something you have <button onclick="readTextFile('file:///temp.txt')">read the txt</button>

Community
  • 1
  • 1
Jin
  • 87
  • 1
  • 1
  • 8

2 Answers2

0

Most browsers implement security restrictions that prevent access to file:// URIs via XMLHttpRequest.

You should consider files on the local file system to be off-limits unless explicitly selected by the user via <input type="file">.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks so much for your response! I'm just confirming does this means my code isn't working because of security restrictions rather than incorrect implementation? How do people regularly use XMLhttpRequest despite the security restrictions? – Jin Aug 03 '15 at 19:38
  • They use it to make HTTP requests, to HTTP servers. – Quentin Aug 03 '15 at 19:49
0

Try this instead:

<button onclick="readTextFile('file:///temp.txt')">read the txt</button>
Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28
  • Thanks for catching my mistake! I managed to get the function to start printing out the alerts. However possibly due to security restrictions the function doesn't actually end up reading anything. – Jin Aug 03 '15 at 19:51