Monday, 4 June 2012

Saving Files Client Side

A couple of html5 interfaces that allow you to download files from the client side are:
These haven't quite made it into the browsers, but there are projects on GitHub for both of these interfaces, whilst we wait for them to become main stream. The basic examples on the FileSaver project README are saving both a text file based on an input string, and saving a canvas as an image file (you can already redirect the user to the data url of the canvas object, but this would actually download the file). See: and Anyways, i'll give a little focus on saving a file.

 I have a basic page with a text field to be used as the file name (:P20_FILE_NAME) and a text area with the data that I want to save to a file (:P20_EXPORT_CONTENT). First I need to add a reference to the two interfaces (I just added these into the page header - obviously better to import these files into the app):

<script src="" type="text/javascript">
<script src="" type="text/javascript">

Then we write a function to save that will save the data:

var exportData = function(){
    //Set to download.txt if nothing was specified
    var fileName = $v("P20_FILE_NAME") || "Download.txt";
    var exportContents = $('#P20_EXPORT_DATA').val();
    //notepad.exe doesnt like printing new lines.,
    exportContents = exportContents.replace(/\n\r?/g, '\r\n');
    var bb = new BlobBuilder();
    saveAs(bb.getBlob("plain/text;charset=UTF-8"), fileName);

Along with a button (Save) pointing to the function to initiate the download. See an example: It's probably worth mentioning, because the scripts are loaded directly from github in this example. it won't work properly in IE(9). See