0

Alright, so here's my little problem. I am trying to read a file directly from the script in JavaScript, but I have no idea how.

In order to get my file in a variable, I use this:

  function readSingleFile(e) {
    var file = e.target.files[0]; 
    if (!file) 
      return; 


    var reader = new FileReader();


    reader.onload = function(e) {
    var contents = e.target.result; 
    };

    reader.readAsText(file);}


    document.getElementById('file-input')
    .addEventListener('change', readSingleFile, false);

with this HTML:

<input type="file" id="file-input" />

The main idea is, how do I choose the path of 'file' variable directly in script? Thank you so much!

Mukesh Ram
  • 6,248
  • 4
  • 19
  • 37

1 Answers1

0

The main idea is, how do I choose the path of 'file' variable directly in script?

You can't. It would be a security violation to allow JavaScript code to read any file it wanted from the user's system. That's why if you look at the "path" you get from the input type="file", you'll see a fake path (but likely a real filename) like (on Windows) C:\fakepath\realFileName.txt.

This question is closely related to, though perhaps not quite a duplicate of, Dynamically set value of a file input.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875