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 ?

7
  • Why do not use them?? Commented Sep 21, 2016 at 1: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. Commented Sep 21, 2016 at 1:13
  • That would be a security problem Commented Sep 21, 2016 at 1: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? Commented Sep 21, 2016 at 1: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. Commented Sep 21, 2016 at 1:31

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.