File API - FileReader (readAsText)
HTML
<!DOCTYPE html>
<html>
<head>
<title>File API - FileReader as Text</title>
</head>
<body>
<header>
<h1>File API - FileReader (Text)</h1>
</header>
<label for="files">Select a file: </label>
<input id="files" type="file" />
<output id="result" />
</body>
</html>
CSS
body{
font-family: 'Segoe UI';
font-size: 12pt;
}
header h1{
font-size:12pt;
color: #fff;
background-color: #1BA1E2;
padding: 20px;
}
article
{
width: 80%;
margin:auto;
margin-top:10px;
}
input[type='file']{
margin:10px;
}
JavaScript
window.onload = function() {
//Check File API support
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function(event) {
var files = event.target.files; //FileList object
var output = document.getElementById("result");
console.log(output);
for (var i = 0; i < files.length; i++) {
var file = files[i];
//Only plain text
if (!file.type.match('plain')) continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var textFile = event.target;
var div = document.createElement("div");
div.innerText = textFile.result;
output.insertBefore(div, null);
});
//Read the text file
picReader.readAsText(file);
}
});
}
else {
console.log("Your browser does not support File API");
}
}