Reading text files

by abubelinha

HTML

<p>
    Choose a text file to be displayed below
</p>
<p>
    <input type="file" id="file-input" />
</p>
<p>
    Your text file contains:
    <br />
    <output id="output"></output>
</p>

CSS

#output {
    font-family: monospace;
    padding: 1em;
    display: inline-block;
}

JavaScript

/*
 Adapted from http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
*/
var input = document.getElementById("file-input");
input.addEventListener("change", function(e) {
    var file = e.target.files[0];

    // Only render plain text files
    if (!file.type === "text/plain")
        return;

    var reader = new FileReader();

    reader.onload = function(event) {
        document.getElementById("output").innerText = event.target.result;
    };

    reader.readAsText(file);
});