1

Javascript: I want to read the content of a text file on my desk but without using XMLHttpRequest or input-type-file. I just want to give the path of the file as input to the javascript function. Any help please ?

  • Why do not use them?? – BrTkCa Sep 21 '16 at 01:10
  • I don't want to use XMLHttpRequest because then I need to connect to the server. And I want the reading process to be automatic without the user interaction from the html file. – Fadwa Estuka Sep 21 '16 at 01:13
  • That would be a security problem – Ed Heal Sep 21 '16 at 01:14
  • 1
    You can use `XMLHttpRequest()` without connecting to a server. _"And I want the reading process to be automatic without the user interaction"_ Are you trying to read files at user filesystem? Without user being aware that their filesystem is being read? – guest271314 Sep 21 '16 at 01:15
  • i tried to use XMLHttpRequest but it gives me error: javascripttt.js:16 XMLHttpRequest cannot load file:///C:/Users/Fadwa/Desktop/testTxt.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. – Fadwa Estuka Sep 21 '16 at 01:31
  • imagine going to any site they can read a file off your computer.... yikes – epascarello Sep 21 '16 at 01:38
  • @FadwaEstuka _"i tried to use XMLHttpRequest but it gives me error"_ Are you trying at chrome browser? See [Jquery load only working in firefox?](http://stackoverflow.com/q/32996001/2801559) – guest271314 Sep 21 '16 at 01:44

2 Answers2

2

Here is a code snippet to do such a thing. I am afraid that you need to file selector due to the sandbox.

<html>
<head>
<title>Example reading a file</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
  function handleFileSelect(evt) {
    var reader = new FileReader();

    reader.onload = function(e) {
      console.log(reader.result);
    };

    reader.readAsText(this.files[0]);
  }

  $(document).ready(function () {
    $('#file').change(handleFileSelect);
  });

</script>
</head>
<body>

<input type="file" id="file" name="files" />

</body>
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

Unfortunately, reading local files in JavaScript without using the File API or an XMLHttpRequest (XHR) request is not possible. This is due to security concerns; allowing JavaScript to access local files on a user's device may result in security vulnerabilities.

XMLHttpRequest request means .get(), .fetch(), xhr()

To read remote file you need xhr request, and to read local files e.g example.text you are required input type="file", and write JS code for it and user will manually choose that file and new FileReader() method to read file content.

Summarize: If you want to add hard-coded file path, and want JavaScript to read that file content, But unfortunately it is not possible.