Javascript HTML5 文件 API:如何查看 readAsText() 的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13729301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 File API: How to see the result of readAsText()
提问by user32262
When readAsText()function is completed the result is stored in .result
当readAsText()函数完成时,结果存储在.result
How do I see if the content of the file read are correct in .result?
如何查看读取的文件内容是否正确.result?
fr = new FileReader();
fr.readAsText(file);
var x = fr.result;
console.log(x); //does not display anything on console
Now how do I display the .resultobject to verify the the content?
现在如何显示.result对象以验证内容?
回答by lostsource
readAsTextis asynchronous, so you would need to use the onloadcallback to see the result.
readAsText是异步的,因此您需要使用onload回调来查看结果。
Try something like this,
尝试这样的事情,
var fr = new FileReader();
fr.onload = function(e) {
// e.target.result should contain the text
};
fr.readAsText(file);
Further information here,
更多信息在这里,
回答by Glen Pierce
This is a complete html and vanilla javascript example that creates a simple file input and a file reader that reads the file with FileReader.readAsText()then writes the text content of that file to the console. This works well for files like .txt or .csv.
这是一个完整的 html 和 vanilla javascript 示例,它创建一个简单的文件输入和一个读取文件的文件阅读器,FileReader.readAsText()然后将该文件的文本内容写入控制台。这适用于 .txt 或 .csv 等文件。
There are also FileReader.readAsArrayBuffer(), FileReader.readAsBinaryString(), and FileReader.readAsDataURL()which might work better for other use cases. I also recommend reading https://developer.mozilla.org/en-US/docs/Web/API/FileReader
还有FileReader.readAsArrayBuffer(), FileReader.readAsBinaryString(), 和FileReader.readAsDataURL()可能更适合其他用例。我还建议阅读https://developer.mozilla.org/en-US/docs/Web/API/FileReader
Note: Users can select multiple files to include in the input, this code will only read the first of those files (as you can see in the reference to the [0] element in event.target.files.
注意:用户可以选择多个文件以包含在输入中,此代码将仅读取这些文件中的第一个(如您在event.target.files.
<html>
<head>
<script>
window.onload = function(event) {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
var fileReader = new FileReader();
fileReader.onload = function(event) {
console.log(event.target.result);
}
var file = event.target.files[0];
fileReader.readAsText(file);
}
</script>
</head>
<body>
<input type="file" id="fileInput">
</body>
</html>

