最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to programmatically select local file in input type="file" - Stack Overflow

programmeradmin1浏览0评论

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

Share Improve this question edited Mar 31, 2016 at 22:26 daylight asked Mar 31, 2016 at 22:23 daylightdaylight 9911 gold badge7 silver badges13 bronze badges 4
  • 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
Add a ment  | 

2 Answers 2

Reset to default 6

You 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

发布评论

评论列表(0)

  1. 暂无评论