简体   繁体   English

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

[英]How to open a local disk file with JavaScript?

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 security reasons.浏览器不允许以这种方式打开本地文件,可能是出于安全原因。 I want to use the file's data in the client side.我想在客户端使用文件的数据。 How can I read local file in JavaScript?如何在 JavaScript 中读取本地文件?

Here's an example using FileReader :这是使用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>


Specs眼镜

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

Browser compatibility浏览器兼容性

  • IE 10+浏览器 10+
  • Firefox 3.6+火狐 3.6+
  • Chrome 13+铬 13+
  • Safari 6.1+ Safari 6.1+

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

The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files. HTML5 fileReader 工具确实允许您处理本地文件,但这些必须由用户选择,您不能在用户磁盘上查找文件。

I currently use this with development versions of Chrome (6.x).我目前在 Chrome (6.x) 的开发版本中使用它。 I don't know what other browsers support it.我不知道其他浏览器支持它。

Because I have no life and I want those 4 reputation points so I can show my love to (upvote answers by) people who are actually good at coding I've shared my adaptation of Paolo Moretti 's code.因为我没有生命,我想要这 4 个声望点,所以我可以向真正擅长编码的人表达我的爱(支持答案)我分享了我对Paolo Moretti代码的改编。 Just use openFile( function to be executed with file contents as first parameter ) .只需使用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>

Try尝试

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

but user need to take action to choose 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>

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

Consider reformatting your file into javascript.考虑将您的文件重新格式化为 javascript。 Then you can simply load it using good old...然后你可以简单地使用旧的加载它......

<script src="thefileIwantToLoad.js" defer></script>

Here is how to do it in typescript if Blob is good enough (no need to convert to ByteArray/String via FileReader for many use-cases)如果 Blob 足够好,这里是如何在打字稿中执行此操作(对于许多用例,无需通过 FileReader 转换为 ByteArray/String)

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

here is how to do it in vanilla javascript这是如何在香草javascript中做到这一点

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

It is not related to "security reasons" .它与“安全原因”无关。 And it does not matter if it local or file on network drive.它是本地的还是网络驱动器上的文件都没有关系。 The solution for Windows OS could be IIS - Internet Information Services and this is some details : Windows 操作系统的解决方案可能是IIS - Internet Information Services ,这是一些细节:
To open file in browser with Java Script window.open() , the file should be available on WEB server.要在浏览器中使用 Java Script window.open() 打开文件,该文件应该在 WEB 服务器上可用。
By creating Virtual Directory on your IIS that mapped to any physical drive you should be able to open files.通过在映射到任何物理驱动器的 IIS 上创建虚拟目录,您应该能够打开文件。 The virtual directory will have some http: address.虚拟目录会有一些 http: 地址。 So instead of window.open("file:///D:/Hello.txt");所以代替window.open("file:///D:/Hello.txt");
You will write window.open("http://iis-server/MY_VIRTUAL_DRIVE_D/Hello.txt");你会写window.open("http://iis-server/MY_VIRTUAL_DRIVE_D/Hello.txt");

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

You can't.你不能。 New browsers like Firefox, Safari etc. block the 'file' protocol. Firefox、Safari 等新浏览器会阻止“文件”协议。 It will only work on old browsers.它仅适用于旧浏览器。

You'll have to upload the files you want.你必须上传你想要的文件。

Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. Javascript 通常无法在新浏览器中访问本地文件,但可以使用 XMLHttpRequest 对象读取文件。 So it is actually Ajax (and not Javascript) which is reading the file.所以它实际上是 Ajax(而不是 Javascript)正在读取文件。

If you want to read the file abc.txt , you can write the code as:如果要读取文件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();

Now txt contains the contents of the file abc.txt.现在txt包含文件 abc.txt 的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM