如何用Javascript打开本地磁盘文件? [英] How to open a local disk file with Javascript?

查看:247
本文介绍了如何用Javascript打开本地磁盘文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图打开文件

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

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

The browser does not allow opening a local file this way, probably for security reasons. I want to use the file's data in the client side. How can I read local file in Javascript?

推荐答案

以下是使用 FileReader

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>

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


  • IE 10 +

  • Firefox 3.6 +

  • Chrome 13 +

  • Safari 6.1 +

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

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

这篇关于如何用Javascript打开本地磁盘文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆