krmax44 krmax44 - 3 months ago 38
Android Question

How to create a folder on the internal storage?

I'm searching a way to create a directory in Cordova for Android on the internal storage (not the

www
dir), so that I have a path like:


  • /mnt/sdcard/myfolder/

  • /sdcard/myfolder/

  • /storage/emulated/0/myfolder/



(these paths are physically the same)

I've found some scripts working within the
www
directory, but how can I create a folder on the internal storage?

Thanks in advance!

Answer

This sample code lets you create folder in the external root directory in Android and documents folder in iOS:

function writeFile() {
        if (sessionStorage.platform.toLowerCase() == "android") {
            window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
        } else {
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
        }
}    

function onError(e) {
    alert("onError");
};

function onFileSystemSuccess(fileSystem) {
    var entry = "";
    if (sessionStorage.platform.toLowerCase() == "android") {
        entry = fileSystem;
    } else {
        entry = fileSystem.root;
    }
    entry.getDirectory("Folder_Name", {
        create: true,
        exclusive: false
    }, onGetDirectorySuccess, onGetDirectoryFail);
};

function onGetDirectorySuccess(dir) {
    dir.getFile(filename, {
        create: true,
        exclusive: false
    }, gotFileEntry, errorHandler);
};

function gotFileEntry(fileEntry) {
    // logic to write file in respective directory
};

function errorHandler(e) {
    // handle error
}