0

The code below is what I have currently. I want to alert(reader.result) outside of onload, but it always returns null. Shouldn't reader.result keep its result after readAsText() is called and finishes?

To be more specific, my final goal is to read the text within files and then save it in a variable for future use. I've just been using alerts as debugging tools (probably bad, I know).

<input type="file" id="fileinput" />
<script type = "text/javascript" id="00">
    var contents = [];
    function readAFile(evt)
    {
        var reader = new FileReader();
        var test
        var file = evt.target.files[0];

        if (file)
        {

            reader.onload = function (element) {
                alert("in onload");
                this.result = element.target.result;
                alert(reader.result);
            };
            reader.onerror = function (element) {
                alert("reader.onerror called - could not load");
            };

            reader.readAsText(file);
            alert(reader.result);

        }
        else
        {
            alert("if(file) returned false - could not load");
        }

    }

    document.getElementById('fileinput').addEventListener('change', readAFile, false);
4

1 回答 1

0
<!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(reader)
        {
            return function()
            {
                var contents = reader.result;
                var lines = contents.split('\n');
                //////
                document.getElementById('container').innerHTML=contents;
            }
        })(reader);

        reader.readAsText(f);
    }
}
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</html>
于 2014-09-25T11:33:04.967 回答