-2

I am trying to make a text file reader for a library I am making.

It returns the path. How can I make it to return the contents of a file?

function alertText() {
    var text = document.getElementsByTagName("input")[0].value;
    alert(text)
}
<input type="file" onchange="alertText();">

Thank you.

fiza khan
  • 1,280
  • 13
  • 24
EthanZone Coding
  • 177
  • 2
  • 12
  • should be duplicated,check [mdn](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file) please – xianshenglu Sep 22 '18 at 08:17
  • 1
    Possible duplicate of [Reading uploaded text file contents in html](https://stackoverflow.com/questions/31746837/reading-uploaded-text-file-contents-in-html) – Mohammad Sep 22 '18 at 08:17

1 Answers1

1

Try below function, it will give you file content in "fileContent" variable:

function alertText() {
  var file = document.getElementsByTagName("input")[0].value;

  var reader = new FileReader(); 
  reader.onload = function (evt) {  //When file is loaded.
    var fileContent = evt.target.result; //event.target.result is the file content     
  }
  reader.readAsText(file, "UTF-8");
}