Tuesday, December 1, 2009

File Open and Save Buttons in HTML

HTML is designed for the big bad Internet, but if you use it as a format for interaction over a local network, as in our case, the security restrictions get rather annoying. The problem with the multipart form approach described below is that you don't have the path to the original file. I wanted to load a specific file, edit the contents and save it back – all in a HTML form. The loading worked – sort of – but the saving was impossible.

The Answer

What I did to get around the security restrictions was to define two applets, one an OPEN button, and the other a SAVE button. Each button creates a JFileChooser with appropriate settings. The code for this is trivial and is just a few lines of toy Java-SE. (I leave this as an exercise for the reader!) I pass in two parameters to the OPEN button applet: the name of the Javascript function I want to call to set a text field on the HTML page, and the id of that field. For the SAVE button I only pass in the name of the Javascript function to retrieve the file path from that field. This is called via LiveConnect, which is contained in the Netscape plugin.jar library that is included in every Java installation. Basically this technology allows you to call any Javascript function in the HTML page that the applet is embedded in. Using these simple tools I fashioned a pretty good lookalike <input type="file"/> field that actually works. One condition for this to work is that the two applets have to be in a signed jar along with the plugin.jar contents. Otherwise security prevents it from accessing the local file system. Just try to do this in standard HTML, after clicking on the 'SAVE' button:

No comments:

Post a Comment