Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file from local directory in Javascript

I need to read a file from a specific path in the hard drive of my computer using Javascript (or using JQuery, it doesn't matter). I have been searching in Google but the things that I found are not really helpful. The closest thing that I have is:

  function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0]; 

    if (f) {
      var r = new FileReader();
      r.onload = function(e) { 
          var contents = e.target.result;
        alert( "Got the file.\n" 
              +"name: " + f.name + "\n"
              +"type: " + f.type + "\n"
              +"size: " + f.size + " bytes \n"
              + "starts with: " + contents.substr(1, contents.indexOf("\n"))
        );  
      }
      r.readAsText(f);
    } else { 
      alert("Failed to load file");
    }
  }

  document.getElementById('fileinput').addEventListener('change', readSingleFile, false);

It allows to select a file using a file chooser, and then it display the contents of the file. I need to do a program that reads a file in which you give the location explicitly, for example c:\files\test.txt, and it prints the contents of the test.txt file.

I Googled this a lot without success, any help is welcome.

like image 806
Vito Avatar asked Apr 11 '26 12:04

Vito


1 Answers

Someone correct me if I'm wrong but as far as I know this is not possible in JavaScript due to security concerns.

If it were, a web page could grab any file on your file system without your consent or without you knowing. This is a major security concern so I dont believe it is possible.

A user must be given the option to choose a file from their file system knowingly.

like image 199
egucciar Avatar answered Apr 13 '26 02:04

egucciar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!