简体   繁体   English

上传多个文本文件并使用jquery在屏幕上预加载

[英]Upload multiple text-files and pre-load on screen with jquery

I'm trying to show on screen the content from some text-files that I'm select to upload. 我试图在屏幕上显示我选择上传的一些文本文件的内容。 But is only showing the last file. 但是只显示最后一个文件。 Can someone tell me why this happend and what can I do to show the content from all files? 有人可以告诉我为什么会这样吗,我该怎么做才能显示所有文件中的内容?

HTML 的HTML

<input type="file" id="file_upload" accept='text/plain' multiple><br>
<span id="output"></span>

Script 脚本

$('#file_upload').on("change", function(){ 
    var reader = new FileReader();

    for (var i = 0, f; f = $(this).get(0).files[i]; i++) {
        var reader = new FileReader();

        $('#output').append('<br>');            
        $('#output').append('<div>'+'<strong>'+$(this).get(0).files[i].name+'</strong>'+'</div>');
        reader.readAsText($(this).get(0).files[i]); 

        reader.onload = function(){
            var text = reader.result;
            $('#output').append('<div>'+reader.result.substring(0, 200)+'</div>');
        };

    }

});

reader is being overwritten every loop iteration, when the onload callback fires the value of reader will be the one that was last created and not the one the callback is bound to. reader在每次循环迭代时都会被覆盖,当onload回调触发时,reader的值将是最后创建的值,而不是回调绑定的值。
Since the callback is bound to its respective reader you can use the this keyword to reference it, the event parameter of the onload callback can also be used to identify the correct reader. 由于回调绑定到其各自的阅读器,因此您可以使用this关键字对其进行引用,因此onload回调的event参数也可以用于标识正确的阅读器。

    reader.onload = function(e){
        var text = this.result;
        //var text = e.target.result;
        $('#output').append('<div>'+text.substring(0, 200)+'</div>');
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM