I'm making extension for firefox, and I want to my extension open a file like "file:///home/blahblah/foo.txt" and then put content of this file in text area. Its easy with files "http://", but i cant do this with "file://"
+1
A:
when working with local files you have to really "load" them:
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 contains the content as string
Niko
2009-08-17 20:17:36
It should be noted that this doesn't handle non-ASCII characters. There is also a simpler way documented here:https://developer.mozilla.org/index.php?title=en/Code_snippets/File_I%2F%2FO#Simple
sdwilsh
2009-08-17 21:06:09
+1
A:
If you have the URI string for the file (rather than the local path or nsIFile object) then you can also use XMLHttpRequest to read the file's contents.
Neil
2009-10-01 19:18:13