Fadwa Estuka
Fadwa Estuka

Reputation: 31

Javascript: Reading local text file from specific path without XMLHttpRequest and without input-type-file

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 ?

Upvotes: 1

Views: 1402

Answers (2)

Dev Hassam
Dev Hassam

Reputation: 19

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.

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60017

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>

Upvotes: 2

Related Questions