我正在尝试用javascript和Google Chrome应用程序读取本地文件(我认为可能无法通过Chrome),但我看不到解决问题的最新方法。
我可以用下面的代码读取它:
obj.read = function() {
return new Promise(function(resolve){
var xmlhttp = new XMLHttpRequest();
var file_path = 'file_name.xml';
xmlhttp.open('GET', file_path, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
let xml = xmlhttp.responseText;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml, "text/xml");
console.log(xml);
console.log(xmlDoc);
resolve(xmlDoc);
}
}
});
};
但是我应该用
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
console.log(e.target.result);
};
})(file_path);
var file_path = 'file_name.xml';
var file_parts = [
new Blob(['you construct a file...'],{type: 'text/plain'}),
'Same way as you do with blob',
new Uint16Array([33])
];
var file = new File(file_parts, file_path);
reader.readAsText(file);
(复制自https://stackoverflow.com/a/24495213/826815)(我很难找到关于这个话题的文献)
那么,怎么做呢?
第一种方法(对于包中的文件来说是XMLHttpRequest
)是完全有效的,如果您只需要整个文件的话,可能会更容易。
您所说的"第二种方法"是从关于实例化File
对象的问题中提取的,而不是读取实际的文件。这将不允许您读取现有的文件,只是创建一个可以在DOM表单中使用的"虚拟"文件。
有整个HTML FileSystem
API,这是没有实现的任何地方,但Chrome和这样的文档是稀缺的,充满了大可怕的红色警告。你可以实际上使用它的目的,你的状态-读取App自己的文件-从chrome.runtime.getPackageDirectoryEntry
开始,但这可能是多余的在您的特殊情况下,再次,你会很难找到这样做的例子。
我能想到的只有两个理由来打扰这个沉睡的野兽,那就是FileSystem
API的应用程序自己的文件:
- 在运行时,您不知道包含哪些文件。然后您可以使用它来列出文件。罕见,但有可能。
- 你需要一个比"get me the whole thing"更细粒度的访问,例如你只需要一个大文件的一小块。
注意FileSystem
API主要用于Chrome for chrome.fileSystem
Apps API。考虑到Chrome将在Chrome操作系统上支持Chrome应用程序一段时间,它很可能会留下来,尽管是非标准的。
幸存的文档:
- 上面提到的HTML5Rocks文章:探索文件系统api
- 最新的公共标准文件:File API: Directories and System
-
File
API的实际标准文档(您的"第二个示例"涵盖):文件API