Cordova Move File using the file url

Scratch. picture Scratch. · Jan 12, 2015 · Viewed 14.6k times · Source

How can I move a file using the URL I get from the Camera?

neither successCallback nor errorCallback is called by the function moveTo. Can anyone tell me what I am doing wrong and what a possible solution looks like?

function successCallback(entry) {
    console.log("New Path: " + entry.fullPath);
    alert("Success. New Path: " + entry.fullPath);
}

function errorCallback(error) {
    console.log("Error:" + error.code)
    alert(error.code);
}

// fileUri = file:///emu/0/android/cache/something.jpg
function moveFile(fileUri) {
    newFileUri  = cordova.file.dataDirectory + "images/";
    oldFileUri  = fileUri;
    fileExt     = "." + oldFileUri.split('.').pop();

    newFileName = guid("car") + fileExt;

    // move the file to a new directory and rename it
    fileUri.moveTo(cordova.file.dataDirectory, newFileName, successCallback, errorCallback);
}

I am using Cordova version 4.1.2 Also installed the Cordova File Plugin

Answer

QuickFix picture QuickFix · Jan 13, 2015

You're trying to call the function moveTo on a String.

moveTO is not a function of String but of fileEntry. So first thing you need to do is get a fileEntry from your URI.

For that you'll call window.resolveLocalFileSystemURL :

function moveFile(fileUri) {
    window.resolveLocalFileSystemURL(
          fileUri,
          function(fileEntry){
                newFileUri  = cordova.file.dataDirectory + "images/";
                oldFileUri  = fileUri;
                fileExt     = "." + oldFileUri.split('.').pop();

                newFileName = guid("car") + fileExt;
                window.resolveLocalFileSystemURL(newFileUri,
                        function(dirEntry) {
                            // move the file to a new directory and rename it
                            fileEntry.moveTo(dirEntry, newFileName, successCallback, errorCallback);
                        },
                        errorCallback);
          },
          errorCallback);
}