如何使用JavaScript打开本地磁盘文件?规格浏览器兼容性

2022-08-30 01:29:00

我试图打开文件

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

浏览器不允许以这种方式打开本地文件,可能是出于安全原因。我想在客户端使用文件的数据。如何用 JavaScript 读取本地文件?


答案 1

下面是使用 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>

规格

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

浏览器兼容性

  • IE 10+
  • 火狐 3.6+
  • 铬 13+
  • 野生动物园 6.1+

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


答案 2

HTML5 fileReader工具确实允许您处理本地文件,但这些必须由用户选择,您不能在用户磁盘上生根以查找文件。

我目前在Chrome(6.x)的开发版本中使用它。我不知道其他浏览器支持它。