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

我试图打开的文件

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

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

655730 次浏览

你不能。Firefox、Safari等新浏览器会阻止“文件”协议。它只能在旧的浏览器上运行。

你必须上传你想要的文件。

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

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

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的内容。

xmlhttp请求方法对于本地磁盘上的文件无效,因为浏览器安全性不允许我们这样做。但我们可以通过创建快捷方式->右键单击->属性在目标“…”浏览器位置path.exe" append——allow-file-access-from-files。这是在chrome上测试的,但是应该注意,所有的浏览器窗口应该关闭,代码应该从通过这个快捷方式打开的浏览器运行。

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

因为我没有生活,我想要那4个声誉点,这样我就可以向那些真正擅长编码的人表达我的爱(给答案点赞),我分享了我对保罗·莫雷蒂代码的改编。只要使用openFile(函数将以文件内容作为第一个参数执行)即可。

function dispFile(contents) {
document.getElementById('contents').innerHTML=contents
}
function clickElem(elem) {
// Thx user1601638 on Stack Overflow (6/6/2018 - https://stackoverflow.com/questions/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>

试一试

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

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

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


async function read(input) {
msg.innerText = await readFile(input.files[0]);
}
<input type="file" onchange="read(this)"/>
<h3>Content:</h3><pre id="msg"></pre>

这里的其他人对此给出了相当详细的代码。也许当时需要更详细的代码,我不知道。不管怎样,我给其中一个点赞了,但这里有一个非常简化的版本,效果相同:

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.
<button onclick="openFile()">Open a file</button>
<input id="inp" type='file' style="visibility:hidden;" onchange="readFile(event)" />
<pre id="contents"></pre>

考虑将你的文件重新格式化为javascript。 然后你可以简单地使用good old…

加载它
<script src="thefileIwantToLoad.js" defer></script>

如果Blob足够好,下面是如何在typescript中做到这一点(对于许多用例,不需要通过FileReader转换为ByteArray/String)

function readFile({
fileInput,
}: {
fileInput: HTMLInputElement;
}): Promise<ArrayLike<Blob>> {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}

以下是如何在香草javascript中做到这一点

function readFile({
fileInput,
}) {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}


这与“安全原因”无关;. 不管它是本地的还是网络驱动器上的文件。 Windows操作系统的解决方案可能是IIS - Internet信息服务 这是一些细节:
要在浏览器中使用Java Script window.open()打开文件,该文件必须在WEB服务器上可用。
通过在IIS上创建映射到任何物理驱动器的虚拟目录,您应该能够打开文件。 虚拟目录将有一些http:地址。 所以不是 window.open("file:///D:/Hello.txt");
你将写入window.open("http://iis-server/MY_VIRTUAL_DRIVE_D/Hello.txt");