I want read a local txt file with javascript on chrome browser. So, I use <input type="file" .../>
and when I select any txt file, I read it. But I dont want select file. I need to load the file with the file path. How is this possible?
Thanks
I want read a local txt file with javascript on chrome browser. So, I use <input type="file" .../>
and when I select any txt file, I read it. But I dont want select file. I need to load the file with the file path. How is this possible?
Thanks
- 3 javascript running in a browser doesn't have unmitigated access to the files on the filesystem. – RJM Commented Mar 31, 2016 at 22:26
-
I am not quite sure how to do it in Vanilla JavaScipt .. But using jQuery, you could use something like:
$('#your_div').load("path/to/file/textfile.txt");
-- AND this file MUST reside on the outward facing side of the website ... Otherwise @RJM is correct .. – Zak Commented Mar 31, 2016 at 22:27 - If selecting the file in the dialog takes too much time and it bothers you you can implement drag and drop – Tamas Hegedus Commented Mar 31, 2016 at 22:31
- @Zak, I don't think that works for local files, just files on the server. (Sorry, just saw your edit) :-) – RJM Commented Mar 31, 2016 at 22:31
2 Answers
Reset to default 6You can't do this. This is obviously because of security implications: imagine if any website you visit could read your FileZilla preferences file, which contains all your unencrypted FTP passwords? I bet you wouldn't like that.
You have to obtain a File
reference (e.g. from an event handler) before being able to manipulate it. More info.
if you want to read file data opened from file dialog:
function readFile(){
var t = document.getElementById("file")
var o = new FileReader();
o.onload = function(t) {
console.log(t.target.result);
}
o.readAsText(t.files[0]);
}
edit: you can't just open files without selecting it first