0

I am trying to have a user click on a "load file" button to choose a file for the webpage. But I can't seem to get the actual file, just the name and when it was last modified. I need to run some JS code on that file, so I just need the actual text. I don't need to put it in the web page, but I just thought that would be a good way to display it. Here's my HTML:

<!DOCTYPE html>
<html>
<head>
    <title></title>

</head>
<body onclick="update_loc(event)"">
  <center><canvas width="400" height="400" id="myCanvas" style="border: 1px solid; border-color: #000000"></canvas></center>
  <script src="./js.js"></script>
  <input type="file" id="myFile">
  <p id="output">YO</p>
</body>
</html>

And my JS:

var reader;
var file;
setTimeout(test_file, 500);
function test_file() {
  setTimeout(test_file, 500);
  file = document.getElementById("myFile").files[0];
  console.log(document.getElementById("myFile").files);
  reader = new FileReader();
  reader.onload = function (e) {
    var textArea = document.getElementById("output");
    textArea.value = e.target.result;
  };
  reader.readAsText(file);
}

I could not figure out how to copy and paste the chrome log, but I just got the file name and time in a "FileList" object.

Neil Macneale
  • 321
  • 4
  • 13
  • This can help you get to your answer: https://stackoverflow.com/questions/371875/local-file-access-with-javascript – Darkisa Jun 15 '17 at 20:15

1 Answers1

1

Try this:

<input type="file" id="files" name="files[]" multiple />
    <output id="list"></output>

    <script>
      function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // files is a FileList of File objects. List some properties.
        var output = [];
        for (var i = 0, f; f = files[i]; i++) {
          output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                      f.size, ' bytes, last modified: ',
                      f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                      '</li>');
        }
        document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
      }

      document.getElementById('files').addEventListener('change', handleFileSelect, false);
    </script>

For more info about how to read and manipulate those files (in this examples is for multiple files) check this url

Yuri Pereira
  • 1,945
  • 17
  • 24