Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

javascript - 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('
');

            })(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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('
');
                //////
                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('
');
            //////
            document.getElementById('container').innerHTML=contents;
        };

        reader.readAsText(f);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...