Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - parameter is not of type 'Blob'

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 the element in the browser. What am I doing wrong?

Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.

<!DOCTYPE html>
    <html>
    <body>

    <p>This example uses the addEventListener() method to attach a click event to a button.</p>

    <button id="myBtn">Try it</button>
    <pre id="file"></pre>

    <script>
    document.getElementById("myBtn").addEventListener("click", function(){
       var file = "test.txt"
       var reader = new FileReader();

       document.getElementById('file').innerText = reader.result;
   
       reader.readAsText(file);

    });
    </script>

    </body>
    </html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've made a couple of errors.

The one that the error message is complaining about is that you are trying to select a file using a hard coded string. You cannot determine which file gets loaded. The File API will only allow you to read files that are selected by the user via a File input.

The second is that you are trying to read the result property of the reader before you've read the file. You need an event handler to do that (because file reading, like Ajax, is asynchronous).

document.getElementById("myBtn").addEventListener("click", function() {

  var reader = new FileReader();
  reader.addEventListener('load', function() {
    document.getElementById('file').innerText = this.result;
  });
  reader.readAsText(document.querySelector('input').files[0]);

});
<input type="file">
<button id="myBtn">Try it</button>
<pre id="file"></pre>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...