这是我的代码。我正在尝试将treeContent传递出read.onload函数。我无法使其正常工作。
控制台显示:外部未定义index.html:18内部的你好世界index.html:15
<!DOCTYPE html>
<html>
<head>
<title>File reader</title>
<meta charset="UTF-8" />
</head>
<body>
<script>
function read(e) {
let reader = new FileReader();
reader.onload = function (e) {
const treeContent = reader.result;
window.file = treeContent;
console.log('inner ' + window.file);
};
reader.readAsText(e.target.files[0]);
console.log('outer '+ window.file);
}
</script>
<input type="file" onchange="read(event)" />
</body>
</html>
从您发布的内容来看,您似乎从未读取任何文件。您在代码中的某个位置应调用reader.readText(fileToRead)..
看看这个最低限度的工作示例:
<!DOCTYPE html>
<html>
<head>
<title>File reader</title>
<meta charset="UTF-8" />
</head>
<body>
<script>
function read(e) {
let reader = new FileReader();
reader.onload = function (e) {
const treeContent = reader.result;
console.log(treeContent);
};
reader.readAsText(e.target.files[0]);
}
</script>
<input type="file" onchange="read(event)" />
</body>
</html>
编辑
如果需要在另一个函数中访问treeContent,则应在onload函数内部调用该函数:
function read(e) {
let reader = new FileReader();
reader.onload = function (e) {
const treeContent = reader.result;
treeContentProcessor(treeContent);
};
reader.readAsText(e.target.files[0]);
}
function treeContentProcessor (content) {
//here is where treeContent is required
console.log(content);
}