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

时间:2019-01-02 18:56:26

标签: javascript filereader

我正在尝试从输入中加载文件,然后使用filereader读取文件。现在,只要单击按钮,我就会收到此错误。

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:

$("#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.")
})

我希望文件先加载然后执行。

1 个答案:

答案 0 :(得分:0)

在执行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();
})