parameter is not of type 'Blob'

后端 未结 4 888
野趣味
野趣味 2020-12-17 09:41

I have written the code below to display the text from a local file using the file API but when I click the button, nothing happens. I get the following error when I inspect

4条回答
  •  隐瞒了意图╮
    2020-12-17 10:01

    As the others said, I noticed that the onload event is what's missing.

    So I have a couple of different ways of showing how to make the reader do something, one for doing the readAsText and one for getting the data as a base64 byte string using readAsDataURL, which is better, in my opinion, since you don't have to worry about Unicode and other weird question mark characters. To see them in action, just flip the call in the listener between uploadFile(); and uploadFile1();. And I show a couple of different ways you can grab the file object, as well:

    document.getElementById("myBtn").addEventListener("click", function() {
      uploadFile1();
    }); 
    
    function uploadFile1(){
      var f = myInput.files[0];
      var reader = new FileReader();
      reader.onload = processFile(f);
      reader.readAsText(f); 
    }
    
    function uploadFile(){
      var f = document.querySelector('input').files[0];
      var reader = new FileReader();
      reader.onload = processFile(f);
      reader.readAsDataURL(f); 
    }
    
    function processFile(theFile){
      return function(e) { 
        // Use the .split I've included when calling this from uploadFile()
        var theBytes = e.target.result; //.split('base64,')[1]; 
        document.getElementById('file').innerText = theBytes;
      }
    }
        
    
    

    And normally I would think you should be able to just do:

    Try it
    

    instead of having to add that listener, but it wasn't working in JSFiddle for some reason.

    https://jsfiddle.net/navyjax2/heLmxegn/1/

提交回复
热议问题