如何使用 Javascript FileReader() 打开本地文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30596280/
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
How to open a local file with Javascript FileReader()
提问by Nemo XXX
I would like to modify this codeso that it works with a specific file only, but I can't figure out the correct URL parameter and all the code examples that I've found use a file selection dialog.
我想修改此代码,使其仅适用于特定文件,但我无法找出正确的 URL 参数以及我发现的所有代码示例都使用文件选择对话框。
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "@":
output=output.split("\n").filter(/./.test, /\@/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
Why doesn't it work when I change the code from:
为什么当我从以下位置更改代码时它不起作用:
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
to:
到:
<body onload="readText('file:///C:/test.txt')">
<div id="main"></div>
</body>
采纳答案by Andrey
Browsers don't give such ability because of security restrictions. You're not allowed to read local files, untill user won't select specific file in file selection dialog (or won't do this with drag-n-drop). That's why all code examples use file selection dialog.
由于安全限制,浏览器不提供这种能力。您不能读取本地文件,直到用户不会在文件选择对话框中选择特定文件(或不会通过拖放操作)。这就是为什么所有代码示例都使用文件选择对话框的原因。
More details Does HTML5 allow you to interact with local client files from within a browser

