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>
Ric
  • 211
  • 2
  • 16

2 Answers2

4

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
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

Community
  • 1
  • 1
Bhaskara
  • 601
  • 9
  • 18