我正在为firefox做扩展,我希望我的扩展程序打开一个文件,如“file:///home/blahblah/foo.txt”,然后将此文件的内容放在文本区域中。文件“http://”很容易,但我不能用“file://”
来做答案 0 :(得分:1)
使用本地文件时,您必须真正“加载”它们:
var file = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/home/blahblah/foo.txt");
if ( file.exists() == false ) {
dup.value = “File does not exist”;
}
var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, 0x01, 4, null);
var fileScriptableIO = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
fileScriptableIO.init(istream);
// parse the xml into our internal document
istream.QueryInterface(Components.interfaces.nsILineInputStream);
var fileContent = "";
var csize = 0;
while ((csize = fileScriptableIO.available()) != 0)
{
fileContent += fileScriptableIO.read( csize );
}
fileScriptableIO.close();
istream.close();
fileContent包含内容为字符串
答案 1 :(得分:0)
如果你有文件的URI字符串(而不是本地路径或nsIFile对象),那么你也可以使用XMLHttpRequest来读取文件的内容。