问题
I would like to modify this code so 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.
<!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>
回答1:
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
来源:https://stackoverflow.com/questions/30596280/how-to-open-a-local-file-with-javascript-filereader