Search code examples
javascriptandroidcordovaphonegap

Saving files in Phonegap


I've been running through docs and everything for the past couple of hours but with no success... I want to download a file from some server and to save it on my phone (the directory where the app stores files that are only visible to my app and are deleted when the app is uninstalled). I would like to store a file and write to it (I've done the download part). With the following code, when I run it, it works and display the text from the "file" but when I search for the file using some file explorer apps, the file that I've "created" is nowhere near to be found.

Cheers!

EDIT Notes: Okay so I've now even tried to create a file on my phone from the computer using a usb connection so I know for a fact the the file exists... The path of the file where I created it from the pc is:

This PC\Galaxy S7 edge\Phone\Android\data\com.phonegap.musicapp2\text.txt

The response code that I get from JSON.stringify(dirEntry) is the following

{"isFile":false,"isDirectory":true,"name":"com.phonegap.musicapp2","fillPath":"/data/user/0/com.phonegap.musicapp2/", "filesystem":"","nativeURL":"file:///data/user/0/com.phonegap.musiapp2/"}

So when I run the code from bellow, it gives me

Error from getFile: {"code":1}

I've looked through the docs and it says that code 1 mean: NOT_FOUND_ERR (http://prntscr.com/n071kx)

"Code from bellow"

function readFile(fileEntry) {

    fileEntry.file(function (file) {
        var reader = new FileReader();

        reader.onloadend = function() {
            DebugConsole.log("Successful file read: " + this.result);
            //  displayFileData(fileEntry.fullPath + ": " + this.result);
        };

        reader.readAsText(file);

    }, onErrorReadFile);
}

window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory, function(dirEntry) {

    DebugConsole.log(JSON.stringify(dirEntry));

    dirEntry.getFile('text.txt', {create: false, exclusive: false}, function(fileEntry) {

        //writeFile(fileEntry, null, isAppend);
        readFile(fileEntry);

    }, function(e) {

        DebugConsole.log('Error from getFile: ' + JSON.stringify(e));
    });
});

Sidenote: App never asks for permission to access my internal storage. I went into Apps/myapp/permissions and it showed that the app doesn't have permission to access the storage. I turned it on but still no luck. I think I need to somehow request storage access from the app but I can't seem to find a way how?


Solution

  • I managed to find a solution with the following

    window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory + "Android/data/app.name/files/", success, fail);