-1

I want to get data from a txt file and set it to a textarea but I don't know how can I do that can you help me?

I get a output like this C:\fakepath\mytext.txt

<textarea  placeholder="Enter Your Code" id="textarea" class="textarea"></textarea>
<button class="butc"  onclick="open()">Add</button>
<script>
function open() {
document.getElementById ('textarea').value = document.getElementById ('file').value ;
}
</script>
  • 2
    Please research your question before posting in accordance with [ask]. In the interest of content quality, duplicative questions aren’t permitted. This is a duplicate of [How to read a local text file in the browser?](https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file-in-the-browser) – esqew Mar 05 '23 at 17:06
  • You may wanna check [How FileReader.readAsText in HTML5 File API works?](https://stackoverflow.com/questions/40146768/how-filereader-readastext-in-html5-file-api-works) – galalem Mar 05 '23 at 17:07

1 Answers1

-1

You just need an <input type='file'/> and a FileReader.

You listen to the change event of the input, and the load event of the reader.

<input id="file-input" type="file" accept=".txt"/>
<textarea id="file-output"></textarea>
const input = document.getElementById('file-input');
const output = document.getElementById('file-output');
input.addEventListener('change', () => outputFileContents(input.files[0]));

function outputFileContents(file: File) {
  const reader = new FileReader();
  reader.readAsText(file);
  reader.addEventListener('load', () => output.value = reader.result);
}

Example: https://stackblitz.com/edit/typescript-dm2hbx?file=index.ts

Docs:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

Chris Hamilton
  • 9,252
  • 1
  • 9
  • 26