简体   繁体   中英

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.

dataControls.js:42 Uncaught (in promise) TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type '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.")
})

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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