Q:

Read text file using FileReader

I've written the following code in an attempt to read the contents of a .txt file
<! DOCTYPE html>
<html>

<input type="file" id="files" name="file" />
<div id="container" style="height: 500px; min-width: 500px"></div>

<script>
    function handleFileSelect(evt) 
    {
        var files = evt.target.files; // FileList object

        // Loop through the FileList and render image files as thumbnails. 
        for (var i = 0, f; f = files[i]; i++) 
        {

            var reader = new FileReader();
            reader.onload = (function(theFile) 
            {
                var contents = theFile.target.result;
                    var lines = contents.split('\n');

            })(f);

            reader.readAsText(f);
        }
    }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</html>

Using firebug I set a break on var contents = theFile.target.result; but nothing is being returned.  Can anyone spot what's wrong? 
Thank you

A:

Try (onload with closure):
function handleFileSelect(evt)
{
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails. 
    for (var i = 0, f; f = files[i]; i++)
    {

        var reader = new FileReader();
        reader.onload = (function(reader)
        {
            return function()
            {
                var contents = reader.result;
                var lines = contents.split('\n');
                //////
                document.getElementById('container').innerHTML=contents;
            }
        })(reader);

        reader.readAsText(f);
    }
}

Or (without closure):
function handleFileSelect(evt)
{
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails. 
    for (var i = 0, f; f = files[i]; i++)
    {

        var reader = new FileReader();
        reader.onload = function(event)
        {
            // NOTE: event.target point to FileReader
            var contents = event.target.result;
            var lines = contents.split('\n');
            //////
            document.getElementById('container').innerHTML=contents;
        };

        reader.readAsText(f);
    }
}

