在android上使用Cordova将文件写入外部(虚拟)存储

时间:2018-02-17 12:34:06

标签: android cordova cordova-plugins

我尝试使用Cordova写入Android平板电脑的外部存储(虚拟SD)。事实上,我正试图访问一个' www。由bitwebserver创建的目录' (一个用于Android的LAMP)。

我有以下代码

但我无法创建该文件,我得到5或9错误代码。

我在这里缺少什么?

谢谢!

<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>

1 个答案:

答案 0 :(得分:0)

在我看来,您的问题是您尝试在应用程序沙盒之外的位置写入模拟SD卡。

从Android 4.4开始,SD卡根目录(/sdcard//storage/emulated/0等)是只读的,因此您无法写入。对于应用程序的沙箱区域之外的任何其他文件夹也是如此。 尝试写入未授权区域将导致调用writer.onerror()函数,错误代码为9:NO_MODIFICATION_ALLOWED_ERR。 因此,尝试写入cordova.file.externalRootDirectory + "/www/test.txt"将解析为/sdcard/www/test.txt并导致上述错误。

您必须写入SD卡上的应用程序存储目录(例如/sdcard/Android/data/your.app.package.id/)。 您可以使用cordova-plugin-file作为cordova.file.externalApplicationStorageDirectory来引用此位置。

有关不同Android版本中SD卡访问的详细信息,请参阅this answer