再次:如何使用 javascript 读取文件

Again: how can I read a file using javascript

我无法找出为什么我的这部分代码不起作用:

var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
var FilePath = dir + "/" + FileName;
var file = new File("FilePath");
var reader = new FileReader();
reader.onload = function(e) {FileText = reader.result;}
reader.readAsText(file); 
alert (FileText);

我认为,其意图很明确:FilePath 包含文件的文件名(通过参数 FileName 传递),其中包含日志数据(纯 ASCII 文本文件,每个日志条目一行),该文件位于与网页相同的目录是 (loc),我想将文本嵌入到我的 html 文档中代码下方的某个位置。

由于记录的行有不同的种类(例如错误、警告、其他 blabla ...),每行都需要被解析和处理。

我打算将 FileText 拆分成一个数组,然后循环遍历它。但是,我无法让 readastext 工作。虽然,根据 FireFox 调试器,FilePath 确实包含正确的字符串,但我得到了 NS_ERROR_FAILURE,根据我找到的关于它的稀疏文档,我必须认为这是最愚蠢的说法 [=26] =].

我发现了很多其他人在乱用文件 API 的帖子,以及从 mozilla 文档中摘录的大量片段,它们对我没有帮助。我读到可能还有其他读取文件的方法,例如通过 Ajax、JQuery ... 但在我走那条路之前 ... 是否真的、真的绝对不可能仅使用普通 JavaScript 来完成我想要的,如果可能的话,谁能提供代码片段?

非常感谢,

阿敏.

您在 "FilePath" 周围有引号:

var file = new File("FilePath");

这意味着它将尝试加载路径为 "FilePath" 的文件。

很确定这就是您想要的:

var file = new File(FilePath);

另一方面,昆汀是完全正确的。如果此代码在网页中为 运行,您将无法访问本地文件。

由于您使用的是 window.location.pathname,因此我假设您在浏览器中并希望使用该代码 "navigate" 根据 URL 路径访问服务器上的文件。

我认为你的整个方法都是错误的,如果有这样的可能会是一个安全问题。

文件API只能用于用户选择的文件,不能用于任何文件。 MDN 描述不言自明:

Using the File API, which was added to the DOM in HTML5, it's now possible for web content to ask the user to select local files, then read the contents of those files. This selection can be done by either using an HTML element, or by drag and drop.

是的,您可以在 File 构造方法中指定任何文件的路径,但这并不意味着您可以访问任何文件。另一段来自 MDN 的摘录:

This only works from privileged code, so web content can't do it. This protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. If you pass a path to the File constructor from unprivileged code (such as web content), an exception will be thrown.

这段代码成功了:

var objXMLhttp = new XMLHttpRequest()
objXMLhttp.open("GET",strFileName,true);
objXMLhttp.send();

此外,必须实现 objXMLhttp.onreadystatechange=function() ... 事件处理程序,这是实际接收数据的代码,如下所示:

objXMLhttp.onreadystatechange=function()
  {
  if (objXMLhttp.readyState==4 && objXMLhttp.status==200)
    {
    var arrContents = objXMLhttp.responseText.split("\n"); // gotcha!
    ....
    }
  }

轻松取胜是对路径执行 ajax 请求...您的页面应该包含 Web 服务器提供的 js 和文件。任何其他方式都需要其他特权,如果您要在没有上传程序的情况下从用户计算机获取文件或类似的东西,将构成安全漏洞