How to open a local disk file with JavaScript?

前端 未结 9 2054
[愿得一人]
[愿得一人] 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);
    
    

    Contents of the file:


    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

提交回复
热议问题