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

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.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments