How to load local file in Javascript using HTML5 FileReader

In HTML5, you can not only upload a file to a server but also process it directly in the browser using Javascript.

This post provides minimal examples of how to use FileReader to do that.

How to read a text file

<html>
<body>
    <input type="file" id="myfile" onchange="onMyfileChange(this)" />
    <script type="text/javascript">
        function onMyfileChange(fileInput) {
            if(fileInput.files[0] == undefined) {
                return ;
            }

            // Example of what information you can read
            // var filename = fileInput.files[0].name;
            // var filesize = fileInput.files[0].size;
            var reader = new FileReader();
            reader.onload = function(ev) {
                var content = ev.target.result; // content is a string
                console.log("Successfully read file");
            };
            reader.onerror = function(err) {
                console.error("Failed to read file", err);
            }
            reader.readAsText(fileInput.files[0]);
        }
    </script>
</body>
</html>

How to read a binary file as ArrayBuffer

<html>
<body>
    <input type="file" id="myfile" onchange="onMyfileChange(this)" />
    <script type="text/javascript">
        function onMyfileChange(fileInput) {
            if(fileInput.files[0] == undefined) {
                return ;
            }

            // Example of what information you can read
            // var filename = fileInput.files[0].name;
            // var filesize = fileInput.files[0].size;
            var reader = new FileReader();
            reader.onload = function(ev) {
                var content = ev.target.result; // content is an ArrayBuffer object
                console.log("Successfully read file");
            };
            reader.onerror = function(err) {
                console.error("Failed to read file", err);
            }
            reader.readAsArrayBuffer(fileInput.files[0]);
        }
    </script>
</body>
</html>