如何使用JavaScript打开本地磁盘文件?


154

我试图用打开文件

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

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

Answers:


238

这是一个使用示例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以上版本
  • 铬13+
  • Safari 6.1+

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


1
仅一秒钟,当我重新加载相同的最后一个文件时,内容没有改变(当我编辑文件文本时,我说的是它的内容)。你能帮我吗?
Hydroper

1
@SamusHands是的,是的,我可以在Safari和Chrome中重现该问题(在Firefox中工作正常)。将输入值设置为null每个onClick事件应该可以解决问题,请参阅:stackoverflow.com/a/12102992/63011
Paolo Moretti 2015年

3
这是一个很好的示例FileReader,但对displayContents上述innerHTML内容进行了评论:请注意,使用不受信任的内容进行此类设置可能是一个安全漏洞。(要亲自查看,请创建一个bad.txt类似以下内容的文件,<img src="/nonexistent" onerror="alert(1);">并查看警报是否已执行-它可能是更恶意的代码。)
ShreevatsaR

2
@ShreevatsaR真的很不错。我的片段只是一个例子,但是您是对的,它不应该养成不良的安全习惯。我换成innerHTMLtextContent。谢谢你的评论。
Paolo Moretti

1
@TeylerHalama您也可以为此使用DOMContentLoaded事件。
保罗·莫雷蒂

59

HTML5的FileReader设施确实允许您处理本地文件,但这些必须由用户来选择,你不能去生根关于用户硬盘寻找文件。

我目前将此用于Chrome(6.x)的开发版本。我不知道其他浏览器支持什么。


3
正确,HTML5现在可以实现。看这里
Flavien Volken 2011年

1
快速浏览参考的规范(最新更新于2012-07-12)显示没有文件写入功能,只能读取文件。
HBP 2012年

26

因为我没有生命,所以我希望获得这4个信誉点,因此我可以向真正擅长编码的人表示爱意(支持答案),我分享了我对Paolo Moretti的编码的改编。只需使用openFile(将文件内容作为第一个参数执行的功能即可)

function dispFile(contents) {
  document.getElementById('contents').innerHTML=contents
}
function clickElem(elem) {
	// Thx user1601638 on Stack Overflow (6/6/2018 - /programming/13405129/javascript-create-and-save-file )
	var eventMouse = document.createEvent("MouseEvents")
	eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
	elem.dispatchEvent(eventMouse)
}
function openFile(func) {
	readFile = function(e) {
		var file = e.target.files[0];
		if (!file) {
			return;
		}
		var reader = new FileReader();
		reader.onload = function(e) {
			var contents = e.target.result;
			fileInput.func(contents)
			document.body.removeChild(fileInput)
		}
		reader.readAsText(file)
	}
	fileInput = document.createElement("input")
	fileInput.type='file'
	fileInput.style.display='none'
	fileInput.onchange=readFile
	fileInput.func=func
	document.body.appendChild(fileInput)
	clickElem(fileInput)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile(dispFile)">Open a file</button>
<pre id="contents"></pre>


2
谢谢,有帮助。尽管请注意clickElem(),您可以直接调用而不是其中包含的代码fileInput.click()。(至少在最新版本的Chrome中)
Venryx

6

尝试

function readFile(file) {
  return new Promise((resolve, reject) => {
    let fr = new FileReader();
    fr.onload = x=> resolve(fr.result);
    fr.readAsText(file);
})}

但是用户需要采取行动来选择文件


我刚刚看到了msg.innerText,这是我第一次了解可以使用ID作为窗口对象的变量名或属性来访问ID标识的某些元素。
fmalina

所以答案是我们做不到。html似乎非常适合文档交互!但并非一切都可以提供。本地文件访问本来很好
yota

@yota-浏览器迫使用户进行交互(并意识到)可能是出于安全原因
KamilKiełczewski

-4

xmlhttp请求方法对于本地磁盘上的文件无效,因为浏览器安全不允许这样做。但是我们可以通过在目标“ ...浏览器中创建快捷方式->右键单击->属性来覆盖浏览器安全性。位置路径。


-7

你不能 诸如Firefox,Safari等新浏览器会阻止“文件”协议。它仅适用于旧的浏览器。

您必须上传所需的文件。


-9

Javascript通常无法在新的浏览器中访问本地文件,但XMLHttpRequest对象可用于读取文件。因此,实际上是Ajax(而不是Javascript)正在读取文件。

如果要读取文件abc.txt,可以将代码编写为:

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();

现在txt包含文件abc.txt的内容。


61
Ajax是JavaScript。
松饼人

4
@TheMuffinMan和XML。(异步Javascript和XML)
Quintec,2014年

9
由于操作员询问如何打开客户端上的文件,而不是服务器上的文件,因此此答案不相关。
托马斯·阮

4
@ThomasNguyen,这个问题是“ javascript打开文件”的第一个google结果,尽管如此,这个答案还是有益的。
弥敦道(Nathan Goings)

@ThomasNguyen我同意,但是如果没有FileReader,可能的解决方法是将文件上传到服务器并从那里读取文件。我还是拒绝了这个答案。
inf3rno
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.