2

I want to read a text file using Javascript. For passing the FileList Object, the available codes use the <input type="file"> with change event, but i want the path of the txt file to be hardcoded inside javascript and the event to be fired onload of document. How can I implement it?? The available code with <input type="file"> is:

<input type="file" id="fileinput" />
<script type="text/javascript">
  function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0]; 
    console.log(evt);
    if (f) {
      var r = new FileReader();
      r.onload = function(e) { 
          var contents = e.target.result;
        alert( "Got the file."+f);  
      }
      r.readAsText(f);
    } else { 
      alert("Failed to load file");
    }
  }
  document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>

2 Answers 2

4

You can't. Access to files on the user's system requires that the user picks them explicitly as a security measure.

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

Comments

0

You cannot browse on the clients disk files. Javascript does not allow. Until and unless a user selects a file you do not have access to the clients (user) file system. However, once the user selects a file you can read the contents of the file. Refer this answer:

JS: Submit HTML file and place file code within div

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.