gpt4 book ai didi

javascript - 使用 FileReader 读取文本文件

转载 作者:技术小花猫 更新时间:2023-10-29 12:38:50 24 4
gpt4 key购买 nike

我编写了以下代码以尝试读取 .txt 文件的内容

<!DOCTYPE html>
<html>

<input type="file" id="files" name="file" />
<div id="container" style="height: 500px; min-width: 500px"></div>

<script>
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object

// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{

var reader = new FileReader();
reader.onload = (function(theFile)
{
var contents = theFile.target.result;
var lines = contents.split('\n');

})(f);

reader.readAsText(f);
}
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</html>

我使用 firebug 在 var contents = theFile.target.result; 上设置了一个中断,但没有返回任何内容。任何人都可以发现问题所在吗?

谢谢

最佳答案

尝试(带闭包的加载):

function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object

// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{

var reader = new FileReader();
reader.onload = (function(reader)
{
return function()
{
var contents = reader.result;
var lines = contents.split('\n');
//////
document.getElementById('container').innerHTML=contents;
}
})(reader);

reader.readAsText(f);
}
}

或者(不关闭):

function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object

// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{

var reader = new FileReader();
reader.onload = function(event)
{
// NOTE: event.target point to FileReader
var contents = event.target.result;
var lines = contents.split('\n');
//////
document.getElementById('container').innerHTML=contents;
};

reader.readAsText(f);
}
}

关于javascript - 使用 FileReader 读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12371970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com