Peter Playz
Peter Playz

Reputation: 15

How To Get .txt File Contents JS

I have a file input like this in html

<input type='file' id='textin'></input>

How Do I Get The Contents Of The .txt File Uploaded?

Upvotes: 0

Views: 48

Answers (1)

GenericUser
GenericUser

Reputation: 3230

You can do this via FileReader.

function previewFile() {
  const content = document.querySelector('.content');
  const [file] = document.querySelector('input[type=file]').files;
  const reader = new FileReader();

  reader.addEventListener("load", () => {
    // this will then display a text file
    content.innerText = reader.result;
  }, false);

  if (file) {
    reader.readAsText(file);
  }
}
<input type="file" onchange="previewFile()" id="textin"><br>
<p class="content"></p>

Upvotes: 2

Related Questions