【问题标题】:Writing a file to external (virtual) storage with Cordova on android在 android 上使用 Cordova 将文件写入外部(虚拟)存储
【发布时间】:2018-02-19 21:23:22
【问题描述】:

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

我有以下代码

但我无法创建文件,我得到 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>

【问题讨论】:

    标签: android cordova cordova-plugins


    【解决方案1】:

    在我看来,您的问题是您试图在应用程序沙箱之外的位置写入模拟 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 引用此位置。

    查看this answer了解不同Android版本的SD卡访问详情。

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 1970-01-01
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 2012-08-11
      • 2019-02-09
      相关资源
      最近更新 更多