How to open a local disk file with JavaScript?

前端 未结 9 2009
[愿得一人]
[愿得一人] 2020-11-22 01:21

I tried to open file with

window.open(\"file:///D:/Hello.txt\");

The browser does not allow opening a local file this way, probably for sec

9条回答
  •  梦如初夏
    2020-11-22 02:02

    Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.

    If you want to read the file abc.txt, you can write the code as:

    var txt = '';
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
      if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
        txt = xmlhttp.responseText;
      }
    };
    xmlhttp.open("GET","abc.txt",true);
    xmlhttp.send();
    

    Now txt contains the contents of the file abc.txt.

提交回复
热议问题