首页 > 解决方案 > 尝试使用 readAsText 时出现 TypeMismatchError

问题描述

我试图在页面启动时加载一个文本文件,但它导致 Reader.readAsText(text.files[0]) 的 TypeMismatchError;

function mm(){
    var text=document.getElementById("aspect");
    const reader=new FileReader();
    reader.onload= function(){
        //var lines = this.result.split('\n');
        console.log(reader.result);};
    reader.readAsText(text.files[0]);}
window.addEventListener("load",mm,false);    


<body>
    <input id="aspect" type="file" value="aspects.txt" style="display:none;" />
</body>

我希望打印文件内容,但我收到了错误消息

标签: javascripthtml

解决方案


您想mm在选择文件而不是在窗口加载时调用,请在文件输入上添加更改事件处理程序。

function mm(){
    var text=document.getElementById("aspect");
    const reader=new FileReader();
    reader.onload= function(){
        //var lines = this.result.split('\n');
        console.log(reader.result);};
    reader.readAsText(text.files[0]);
}


<body>
    <input id="aspect" type="file" value="aspects.txt" onchange="mm()" style="display:none;" />
</body>

推荐阅读