Disco Fever
Disco Fever

Reputation: 147

Writing a file to external (virtual) storage with Cordova on android

I'm trying to write to the external storage (virtual SD) of an android tablet using Cordova. In fact, i'm trying to access a 'www' directory created by 'bitwebserver' (a LAMP for android).

I have the following piece of code

But i can't get to create the file, I either get a 5 or 9 error code.

What am I missing here ?

Thanks !

<script>
    // Wait for Cordova to load
    document.addEventListener("deviceready", onDeviceReady, false);

    // We're ready
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystem, fail);
    }

    function gotFileSystem(fileSystem) {
        fileSystem.root.getFile(cordova.file.externalRootDirectory + "/www/test.txt", {
            create: true,
            exclusive: false
        }, gotFileEntry, fail);
    }

    function gotFileEntry(fileEntry) {
        fileEntry.createWriter(gotFileWriter, fail);
    }

    function gotFileWriter(writer) {
        writer.onwriteend = function (evt) {
            console.log("contents of file now 'some sample text'");
            writer.truncate(11);
            writer.onwriteend = function (evt) {
                console.log("contents of file now 'some sample'");
                writer.seek(4);
                writer.write(" different text");
                writer.onwriteend = function (evt) {
                    console.log("contents of file now 'some different text'");
                }
            };
        };
        writer.write("some sample text");
    }

    function fail(error) {
        console.log(error.code);
        console.log(error);
    }
</script>

Upvotes: 1

Views: 1023

Answers (1)

DaveAlden
DaveAlden

Reputation: 30356

It seems to me your problem is that you're trying to write to the emulated SD card in a location outside of the application's sandbox.

Since Android 4.4, the SD card root (/sdcard/, /storage/emulated/0, etc.) is read-only so you cannot write to it. The same goes for any other folder outside of the application's sandbox area. Attempting to write to an unauthorised area will result in the writer.onerror() function being invoked with error code 9: NO_MODIFICATION_ALLOWED_ERR. So trying to write to cordova.file.externalRootDirectory + "/www/test.txt" will resolve to /sdcard/www/test.txt and result in the above error.

You must write to the application storage directory on the SD card (e.g. /sdcard/Android/data/your.app.package.id/). You can reference this location using cordova-plugin-file as cordova.file.externalApplicationStorageDirectory.

See this answer for details of SD card access in different versions of Android.

Upvotes: 2

Related Questions