Accessing the file system via PhoneGap

2012-09-02

Thought I’d pop up a quick post about accessing the filesystem using PhoneGap on an Android device (I think it’s the same method for iOS but you might be more restricted?). The file system API lets you access files/directories and copy/move/delete/create them as well as read and write to them. It feels a little clunky to me as it’s based on the HTML5 spec which uses a success and failure callback for each call. Still it works well once you figure it out a bit.

First up, set up your usual deviceready event listener.
document.addEventListener("deviceready", onDeviceReady, false);

Next we request the file system from the callback. Now you can pass in either the LocalFileSystem.PERSISTENT or LocalFileSystem.TEMPORARY flag as the first parameter. Temporary will give you access to your applications directory, which can be useful but if you want to read from other parts of the filesystem, start with persistent.
function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail); }
The last two parameters are your success and fail callbacks.

The file system is passed as an object into the success callback and if like me you wanted to get to the root folder and read the files and directories there then your function should look something like below.
function onFileSystemSuccess(fileSystem) { var dirReader = fileSystem.root.createReader(); dirReader.readEntries(dirReadSuccess, dirReadError); }

Finally if all that has worked you’ll get an array of file entries passed to your success callback that you can loop over and grab some properties like whether it is a file or folder and it’s name, etc. Drill in further and repeat.
function dirReadSuccess(entries) { var i; for (i = 0; i < entries.length; i++) { // push into an array or object you want to work with... } }

Hope that helps someone else out as it was a little hard initially for me to work out how to grab a list of files/folders at the device root.


Comments: