How to open a local disk file with JavaScript?

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

    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.
    
    
    

提交回复
热议问题