Twitter: raymondcamden


Address: Lafayette, LA, USA

PhoneGap/Cordova Example - Getting File Metadata (and an update to the FAQ)

08-18-2014 3,668 views Mobile, JavaScript 3 Comments

I decided to move my PhoneGap/Cordova FileSystem FAQ from a Google Doc to my Cordova Examples repository. I figured this would make it a bit easier for folks to edit and simpler for me to commit those changes. You can find the FAQ here:

PhoneGap Cordova File System FAQ

In doing so I decided to quickly knock out one of the questions - how to get metadata about files. This is rather trivial, so my demo app is rather trivial, but hopefully it will help folks. The basic gist is - once you have a FileEntry object, you can then fetch the File object itself (MDN Docs) and fetch various properties. Here is a super simple demo roughly based on the ones I showed earlier. It uses window.resolveLocalFileSystemURL to get index.html.

document.addEventListener("deviceready", init, false);
function init() {
	
	//This alias is a read-only pointer to the app itself
	window.resolveLocalFileSystemURL(cordova.file.applicationDirectory + "www/index.html", gotFile, fail);

}

function fail(e) {
	console.log("FileSystem Error");
	console.dir(e);
}

function gotFile(fileEntry) {

	fileEntry.file(function(file) {
		var s = "";
		s += "<b>name:</b> " + file.name + "<br/>";
		s += "<b>localURL:</b> " + file.localURL + "<br/>";
		s += "<b>type:</b> " + file.type + "<br/>";
		s += "<b>lastModifiedDate:</b> " + (new Date(file.lastModifiedDate)) + "<br/>";
		s += "<b>size:</b> " + file.size + "<br/>";
		
		document.querySelector("#status").innerHTML = s;
		console.dir(file);
	});
}

Here is a sample of it running in iOS. (Be aware - there is a bug with Android that may prevent this from working. It is reported at the Cordova site.)

So - yeah - not rocket science - but hopefully helpful. This "application" can be grabbed from my Cordova repo: https://github.com/cfjedimaster/Cordova-Examples/tree/master/getfiledata.

3 Comments

  • Commented on 08-22-2014 at 11:20 AM
    why is type showing up as null?
    also, is this any better/easier then using AJAX and getting headers?
  • Commented on 08-22-2014 at 11:24 AM
    If I had to guess, it doesn't know what an html file is.

    Is this better? Um... I don't know. :) I've been using files under www/ for my blog posts because it is easier to work with. I think generally folks will probably not be doing that. Does that make sense?
  • Commented on 08-22-2014 at 11:48 AM
    Might make sense but not really getting it :)
    Either way, I believe it's subjective (i.e. what you're used to)...

Post Reply

Please refrain from posting large blocks of code as a comment. Use Pastebin or Gists instead. Text wrapped in asterisks (*) will be bold and text wrapped in underscores (_) will be italicized.

Leave this field empty