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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3582671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:17:51  来源:igfitidea点击:

How to open a local disk file with JavaScript?

javascript

提问by Joval

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 中读取本地文件?

回答by Paolo Moretti

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+
  • Firefox 3.6+
  • Chrome 13+
  • Safari 6.1+
  • 浏览器 10+
  • 火狐 3.6+
  • 铬 13+
  • Safari 6.1+

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

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

回答by HBP

The HTML5 fileReader facilitydoes 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). I don't know what other browsers support it.

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

回答by SignatureSmileyfaceProductions

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. Just use openFile(function to be executed with file contents as first parameter).

因为我没有生命,我想要这 4 个声望点,所以我可以向真正擅长编码的人表达我的爱(支持答案)我分享了我对Paolo Moretti代码的改编。只需使用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>

回答by Kamil Kie?czewski

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>

回答by user2450701

The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.

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

回答by Karanpreet Singh

Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.

Javascript 通常无法在新浏览器中访问本地文件,但可以使用 XMLHttpRequest 对象读取文件。所以它实际上是 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 txtcontains the contents of the file abc.txt.

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

回答by Youssef

You can't. New browsers like Firefox, Safari etc. block the 'file' protocol. It will only work on old browsers.

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

You'll have to upload the files you want.

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