This is a complete html and vanilla javascript example that creates a simple file input and a file reader that reads the file with FileReader.readAsText()
then writes the text content of that file to the console. This works well for files like .txt or .csv.
There are also FileReader.readAsArrayBuffer()
, FileReader.readAsBinaryString()
, and FileReader.readAsDataURL()
which might work better for other use cases. I also recommend reading https://developer.mozilla.org/en-US/docs/Web/API/FileReader
Note: Users can select multiple files to include in the input, this code will only read the first of those files (as you can see in the reference to the [0] element in event.target.files
.
<html>
<head>
<script>
window.onload = function(event) {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
var fileReader = new FileReader();
fileReader.onload = function(event) {
console.log(event.target.result);
}
var file = event.target.files[0];
fileReader.readAsText(file);
}
</script>
</head>
<body>
<input type="file" id="fileInput">
</body>
</html>