Recipe 10.1
Loading Text From a File
Select a plain text file to load into the browser.
Demo
Code
JavaScript
const fileInput = document.querySelector('#file-upload');
const content = document.querySelector('#file-content');
fileInput.addEventListener('change', event => {
const [file] = fileInput.files;
const reader = new FileReader();
reader.addEventListener('load', event => {
content.textContent = event.target.result;
});
reader.addEventListener('error', event => {
console.log('error', event);
});
reader.readAsText(file);
});
HTML
<label for="file-upload" class="form-label">Select File</label>
<input id="file-upload" class="form-control" type="file">
<div class="card my-4">
<div class="card-body">
<pre id="file-content"></pre>
</div>
</div>