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>
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>
Share
Improve this question
asked Jun 2, 2015 at 12:35
Nemo XXXNemo XXX
6912 gold badges15 silver badges38 bronze badges
1
- 2 You cannot read local files like that, the user has to use a file selection dialog or do a file drag and drop in order for the browser to give you access to local files, otherwise it would be a huge security issue – Patrick Evans Commented Jun 2, 2015 at 12:38
1 Answer
Reset to default 11Browsers 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