How to open a local disk file with JavaScript?

前端 未结 9 2039
[愿得一人]
[愿得一人] 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 01:58

    Here's an example using FileReader:

    function readSingleFile(e) {
      var file = e.target.files[0];
      if (!file) {
        return;
      }
      var reader = new FileReader();
      reader.onload = function(e) {
        var contents = e.target.result;
        displayContents(contents);
      };
      reader.readAsText(file);
    }
    
    function displayContents(contents) {
      var element = document.getElementById('file-content');
      element.textContent = contents;
    }
    
    document.getElementById('file-input')
      .addEventListener('change', readSingleFile, false);
    <input type="file" id="file-input" />
    <h3>Contents of the file:</h3>
    <pre id="file-content"></pre>


    Specs

    http://dev.w3.org/2006/webapi/FileAPI/

    Browser compatibility

    • IE 10+
    • Firefox 3.6+
    • Chrome 13+
    • Safari 6.1+

    http://caniuse.com/#feat=fileapi

    0 讨论(0)
  • 2020-11-22 02:02

    Others here have given quite elaborate code for this. Perhaps more elaborate code was needed at that time, I don't know. Anyway, I upvoted one of them, but here is a very much simplified version that works the same:

    function openFile() {
      document.getElementById('inp').click();
    }
    function readFile(e) {
      var file = e.target.files[0];
      if (!file) return;
      var reader = new FileReader();
      reader.onload = function(e) {
        document.getElementById('contents').innerHTML = e.target.result;
      }
      reader.readAsText(file)
    }
    Click the button then choose a file to see its contents displayed below.
    <button onclick="openFile()">Open a file</button>
    <input id="inp" type='file' style="visibility:hidden;" onchange="readFile(event)" />
    <pre id="contents"></pre>

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题