以下代码是我目前的代码。我想在onload之外提醒(reader.result),但它总是返回null。 read.Teult在readAsText()被称为之后是否应该保留其结果并完成?
更具体地说,我的最终目标是读取文件中的文本,然后将其保存在变量中以备将来使用。我刚刚使用警报作为调试工具(可能不好,我知道)。
<input type="file" id="fileinput" />
<script type = "text/javascript" id="00">
var contents = [];
function readAFile(evt)
{
var reader = new FileReader();
var test
var file = evt.target.files[0];
if (file)
{
reader.onload = function (element) {
alert("in onload");
this.result = element.target.result;
alert(reader.result);
};
reader.onerror = function (element) {
alert("reader.onerror called - could not load");
};
reader.readAsText(file);
alert(reader.result);
}
else
{
alert("if(file) returned false - could not load");
}
}
document.getElementById('fileinput').addEventListener('change', readAFile, false);
答案 0 :(得分:0)
<!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(reader)
{
return function()
{
var contents = reader.result;
var lines = contents.split('\n');
//////
document.getElementById('container').innerHTML=contents;
}
})(reader);
reader.readAsText(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</html>