Home > Net >  How To Get .txt File Contents JS
How To Get .txt File Contents JS

Time:12-02

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?

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related