简体   繁体   English

如何先加载文件然后执行FileReader

[英]how to load the file first and then execute FileReader

I am trying to load a file from the input and then reading the file using filereader.Right now I am getting this error as soon i just click on the button. 我正在尝试从输入中加载文件,然后使用filereader读取文件。现在,只要单击按钮,我就会收到此错误。

dataControls.js:42 Uncaught (in promise) TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'. dataControls.js:42未捕获(承诺)TypeError:无法在“ FileReader”上执行“ readAsText”:参数1的类型不是“ Blob”。

HTML:
     <div style="padding:0px;">
        <button id="saveData" type="button" class="btn btn-primary" data-toggle="button" title="Save Data">
            <i class="fa fa-floppy-o" aria-hidden="true"></i>    
        </button>
        <button id="loadData" type="button" class="btn btn-warning" data-toggle="button" title="Will reload the data from the last save">
            <i class="fa fa-reply-all" aria-hidden="true"></i>
        </button>
        <button id="clearData" type="button" class="btn btn-danger" data-toggle="button" title="Clear stored data">
            <i class="fa fa-times" aria-hidden="true"></i>
        </button>
        <input type="file" accept=".data" id="load" on style="display:none" >
        </div>

JS: JS:

$("#loadData").click(async () => {
    if (!grid || !grid.getInstance() || !JSON.parse(localStorage.getItem('data') || "[]").length) {
        alerts.error("No data available to load yet")
        return;
    }

    var input = document.getElementById('load');
    input.click();  
    var file = document.getElementById("load").files[0];
        var reader = new FileReader();
       reader.onload = read;
       function read(evt){
           var text =reader.result;
       }

        reader.readAsText(file);
        var data = reader.result;
        console.log(reader.result)
        grid.setData(JSON.parse(data)).getInstance().loadData()
         alerts.success("Data loaded successfully.")
})

I want the file to load first and then execute it . 我希望文件先加载然后执行。

You'd want to take all of the code from var file... on and wrap it into a function set to input.onload before you execute input.click() 您希望从var file...获取所有代码var file... ,然后将其包装到设置为input.onload的函数中,然后再执行input.click()

 $("#loadData").click(async () => { if (!grid || !grid.getInstance() || !JSON.parse(localStorage.getItem('data') || "[]").length) { alerts.error("No data available to load yet") return; } var input = document.getElementById('load'); input.onload = function(){ var file = document.getElementById("load").files[0]; var reader = new FileReader(); reader.onload = read; function read(evt){ var text =reader.result; } reader.readAsText(file); var data = reader.result; console.log(reader.result) grid.setData(JSON.parse(data)).getInstance().loadData() alerts.success("Data loaded successfully.") } input.click(); }) 

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

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