参数不是'Blob'类型 [英] parameter is not of type 'Blob'
问题描述
我已经编写了下面的代码来使用文件API显示本地文件中的文本,但是当我单击该按钮时,没有任何反应,当我检查浏览器中的元素时,出现以下错误,我的东西错误?
未捕获TypeError:未能在'FileReader'上执行'readAsText':参数1不是'Blob'类型。 >
<!DOCTYPE html> < HTML> <身体GT; < p>此示例使用addEventListener()方法将点击事件附加到按钮。< / p> < button id =myBtn>试试< / button> < pre id =file>< / pre> <脚本> document.getElementById(myBtn)。addEventListener(click,function(){var file =test.txtvar reader = new FileReader(); document.getElementById('file')。innerText = reader.result; reader.readAsText(file);}); < /脚本> < /体> < / html>
<要将文件内容设置为 innerHtml
,您必须先阅读该文件。 loadend
事件仅在文件完全获得时触发,并且您可以无错地访问其版块:
var reader = new FileReader();
var fileToRead = document.querySelector('input')。files [0];
//附加事件,读取结束时将被触发
reader.addEventListener(loadend,function(){
// reader.result包含内容blob作为类型化数组
//我们在DOM中插入文件内容
document.getElementById('file')。innerText = reader.result;
});
//开始读取加载的文件
reader.readAsText(fileToRead);
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 and I get the following error when I inspect the element in the browser, what am I dong 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>
To set File content into innerHtml
you must first read the file. loadend
event fires only when file is fully readed, and you can access its contect without errors:
var reader = new FileReader();
var fileToRead = document.querySelector('input').files[0];
// attach event, that will be fired, when read is end
reader.addEventListener("loadend", function() {
// reader.result contains the contents of blob as a typed array
// we insert content of file in DOM here
document.getElementById('file').innerText = reader.result;
});
// start reading a loaded file
reader.readAsText(fileToRead);
You can read more here - and here
这篇关于参数不是'Blob'类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!