How to open a local file with Javascript FileReader()

我与影子孤独终老i 提交于 2019-12-10 12:59:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!