Source Code: (back to article)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>File Reader Example</title>
</head>
<body>
<h1>Read Text File</h1>
<p>First, choose a text file, then click the 'Read File' button to see your file's contents.</p>
<input type="file" id="fileInput" accept=".txt" />
<button onclick="readFile()">Read File</button>
<pre id="fileContents"></pre>

<script>
function readFile() {
const fileInput = document.getElementById("fileInput");
const file = fileInput.files[0]; // Get the first file selected by the user

if (file) {
const reader = new FileReader();

reader.onload = function (e) {
const contents = e.target.result;
document.getElementById("fileContents").textContent = contents;
};

reader.onerror = function (e) {
console.error("Error reading file:", e.target.error.message);
};

reader.readAsText(file); // Read the file as text
} else {
alert("Please select a file.");
}
}
</script>