Home > Uncategorized > Saving files locally using PhoneGap

Saving files locally using PhoneGap

One of the quintessential differences between an application and a web page is that applications are trusted to read and write to the hard drive on the machine it is running on. With the exception of limited space given under certain circumstances for Isolated storage (Silverlight), Cookies and Localstorage (5Mb ~ or effectively 2.5 Mb of text), web pages aren’t trusted enough to read and write to your hard drive, and rightly so.

With Apps, there is an elevated level of trust, so you can read and write files within your application “Sandbox”, i.e. space devoted to your app, and no-one else’s.  With smartphones coming now with up to 64 GB of storage, this gives plenty of opportunity to download images, video and content for offline use.

I just learned this morning how to use PhoneGap’s File API, – This example applies specifically to version 2.9.0 on iOS, but it should be equally applicable to other versions, and Android.

First off, you need to get a handle to the local file system, which you can do on the device ready event like so:

var fileSystem = null;

document.addEventListener(“deviceready”, onDeviceReady, false);

function onDeviceReady()
console.log(“Device Ready”);
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function gotFS(fs)
console.log(“Got File System Reference”);
fileSystem = fs;
}, fail);

Here the variable fileSystem is declared with global scope, and I have selected Temporary storage. Temporary storage is not designed for “mission critical” or user generated content, just things that can be downloaded again, if need be. Ideal for short-term caching.

Then, I have written a handy function to store this data onto disk:

function createFileWithContent(filename, content)
{create: true, exclusive: false},
function gotFileEntry(fileEntry) {
console.log(“Got File Entry Reference”);
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
}, fail);
}, fail);

This function writes text content to a file. You don’t worry about the path, since this is dictated by the operating system.

To read this back in, you can use simple ajax, as you would read a local file off disk.

The fail function is omitted here, but it can be a simple console.log, or something more advanced, depending on how you wish the app to respond to errors in the process of saving data.


Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: