1

I have been struggling with reading local files from the file path in javascript. I have tried XMLHttpRequest to no avail.

function readFile(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 text = rawFile.responseText;
        document.write(text);
      }
    }
  }
  rawFile.send(null);
}

window.onload = function() {
  readFile("text.txt");
}

I have also tried FileReader but the way I understand it is that it doesn't read files from a string file path; or how can I create a File object to use in FileReader. I also don't want to use node fs module. Could anyone help out on the best and surest way to read local files from the file path? THANKS

1 Answer 1

4

Security restrictions in most browsers make this impossible.

Webpages are not allowed to select files from the user's computer to make accessible to JavaScript. Only the user (e.g. via a file <input>) can do that.

Sign up to request clarification or add additional context in comments.

7 Comments

ok thanks... is there a way I can create a File object or something of the sort without accessing local files to use in FileReader?
If you don't want to access local files with it … what do you want to access with it?
I could let's say test FileReader using jasmine
You'd probably need to mock the FileReader object entirely to do that.
how would I do that?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.