« The Network IS the Computer: Ajax on Desktop Classfieds based on Tagging and RSS »
Saving and Loading Files from Web Pages via AJAX
Posted February 16, 2006 – 2:32 pm by Yakov Shafranovich in ProgrammingI recently ran across a nifty project called “TiddlyWiki”. One of the things that struct me as interesting features from the programming point of view is the fact that it is able to load and save itself to the user’s hard drive using Javascript without any kind of server side support. After digging more into the source code (which is licensed under a BSD license), it seems pretty straight forward and simple and I am going to describe it in this post (WARNING: all this code is based on the TiddlyWiki code covered under BSD license (for full license terms, see their website).
The trick to saving and opening data in Javascript is not using Javascript
Rather this particular hack relies on browser-specific functionality, but it just happens to be that IE, Mozilla AND Opera all expose this functionality via three differents ways. Here is how to save files in IE relying on the Scripting.FileSystemObject functionality:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath,2,-1,0);
file.Write(content);
file.Close();
In Mozilla, the trick is to use two XUL interfaces called “mozilla.org/file/local” and “mozilla.org/network/file-output-stream”:
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.nterfaces.nsILocalFile);
file.initWithPath(filePath);
if (!file.exists())
file.create(0, 0664);
var out = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.nterfaces.nsIFileOutputStream);
out.init(file, 0×20 | 0×02, 00004,null);
out.write(content, content.length);
out.flush();
out.close();
In Opera, this is done by interfacing to the Java Core API via Javascript:
var s = new java.io.PrintStream(new java.io.FileOutputStream(operaUrlToFilename(filePath)));
s.print(content);
s.close();















One Response to “Saving and Loading Files from Web Pages via AJAX”
There is a slight typo in the mozilla implementation:
This:
Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.nterfaces.nsIFileOutputStream);
Should be:
Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
By Andy on Aug 21, 2006