In my PhoneGap/jQuery Mobile app, I\'m currently using PhoneGaps\' Camera API to allow the user to take a photo, which is also stored in the Camera Roll. I\'m setting Destin
Sharing my version which uses promises and resolveLocalFileSystemURL except resolveLocalFileSystemURI because second one is deprecated. It also uses original file name in new created one.
function copyPhotoToAppDir(imageURI) {
if(!imageURI){
console.warn("You need to pass imageURI");
return;
}
var fileNameSplit = imageURI.split("/"),
fileName = fileNameSplit[fileNameSplit.length - 1],
deferred = $q.defer();
var copyPhoto = function(fileEntry) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory("photos", {create: true, exclusive: false}, function(dir) {
fileEntry.copyTo(dir, fileName, onCopySuccess, onFileFail);
}, onFileFail);
}, onFileFail);
};
var onCopySuccess = function onCopySuccess(entry) {
console.log("NEW PATH", entry.fullPath);
deferred.resolve(entry.fullPath);
};
var onFileFail = function (error) {
console.log("COPY FAIL", error);
deferred.reject();
};
window.resolveLocalFileSystemURL(imageURI, copyPhoto, onFileFail);
return deferred.promise;
}
Usage:
var uri = "path1";
copyPhotoToAppDir(uri).then(function(newURI){
console.log(newURI);
});
Multiple URIs usage:
var uriArr = ["path1", "path2"];
copyPhotoPromises = [];
uriArr.forEach(function(val){
copyPhotoPromises.push(copyPhotoToAppDir(val));
});
$q.all(copyPhotoPromises).then(function(values){
console.log("Array with new paths", values);
});
New file URIs will be saved as "/photos/fileName.jpg". To get the absolute path, you can use:
cordova.file.documentsDirectory + newFileUri.substring(1);
I'm using $q from angular here to handle promises but it can be easily changed to jQuery one.
deferred = $q.defer();
would need to be changed to:
deferred = jQuery.Deferred();
Cheers