如何使用cordova文件/文件系统根插件访问外部存储?

时间:2014-04-04 16:24:25

标签: android cordova file-io

问题描述: 我可以使用文件或文件系统根(读取和写入)访问内部存储。但是这样的文件无法从其他应用程序访问。例如,如果我想通过emailComposerPlugin发送此文件,则电子邮件客户端无法访问该文件。 (同样适用于“打开方式”功能。) 如果我将选项{sandboxed: true}更改为false(写入外部存储器),则它不起作用并最终在FileUtils.UNKNOWN_ERR中。当手机与USB断开连接时,我尝试了应用程序,因为有些文档提到在安装到PC上时无法访问外部存储 - 但结果相同。

从我在mailing list上看到的内容应该是可能的。看来我错过了一个关键点?

上下文 我尝试启用为iPhone创建的混合应用程序以在Android设备上运行。为了有一个小游乐场,我创建了一个小型测试项目。

修改 文件系统根目录和文件插件之间似乎存在问题。但我有他们两个的最新版本。 (文件:1.0.1文件系统根:0.1.0) 调试文件系统和文件类显示

private String fullPathForLocalURL(Uri URL) {
    if (FILESYSTEM_PROTOCOL.equals(URL.getScheme()) && "localhost".equals(URL.getHost())) {
        String path = URL.getPath();
        if (URL.getQuery() != null) {
            path = path + "?" + URL.getQuery();
        }
        return path.substring(path.indexOf('/', 1));
        // path = "/cache-external" at this point
        // results in index out of bounds exception

我尝试了什么?

config.xml中

<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external" />

的AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

javascript代码

function createTextDocument(filename, text) {

    cordova.filesystem.getDirectoryForPurpose('cache', {sandboxed: false}, successCallback, failureCallback);

    function successCallback(directoryEntry){
        console.log('directory found (cordova): ' + directoryEntry.toURL());
        console.log('directory found (native) : ' + directoryEntry.toNativeURL());
        directoryEntry.getFile(filename, {create: true, exclusive: false},
            function(fileEntry){
                var filePath = fileEntry.toNativeURL();
                fileEntry.createWriter(
                    function(fileWriter){
                        console.log('start writing to: ' + filePath );
                        fileWriter.write(text);
                        console.log('file written');
                    },failureCallback
                );
            }, failureCallback
        );
    }

    function failureCallback(error){
        console.log('error creating file: ' + error.code);
        // results in code 1000
    }
}

2 个答案:

答案 0 :(得分:13)

在深入挖掘整个主题之后,我想出了:

  • 不需要文件系统根插件。
  • config.xml中需要更多配置。
  • 您需要使用的不是标准的FileApi方式,而是使用以下方式来访问文件。

JavaScript用法:

window.resolveLocalFileSystemURL(path, cbSuccess, cbFail);

@param path: {string} a cordova path with scheme: 
             'cdvfile://localhost/<file-system-name>/<path-to-file>' 
             Examples: 'cdvfile://localhost/sdcard/path/to/global/file'
                       'cdvfile://localhost/cache/onlyVisibleToTheApp.txt'
@param cbSuccess: {function} a callback method that receives a DirectoryEntry object.
@param cbFail: {function} a callback method that receives a FileError object.

config.xml中

<preference name="AndroidPersistentFileLocation" value="Compatibility" />
<preference name="AndroidExtraFilesystems" value="sdcard,cache" />

的AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

答案 1 :(得分:5)

经过几个小时的挣扎,我终于能够通过提供像&#34; files:// pathtofile /&#34;这样的目录来扫描SD卡并获取对文件的访问权限。
我&# 39;提交API和示例项目 https://github.com/xjxxjx1017/cordova-phonegap-android-sdcard-full-external-storage-access-library

使用API​​的示例

new ExternalStorageSdcardAccess( fileHandler ).scanPath( "file:///storage/sdcard1/music" );
function fileHandler( fileEntry ) {
    console.log( fileEntry.name + " | " + fileEntry.toURL() );
}

API源代码

var ExternalStorageSdcardAccess = function ( _fileHandler, _errorHandler ) {

    var errorHandler = _errorHandler || _defultErrorHandler;
    var fileHandler = _fileHandler || _defultFileHandler;
    var root = "file:///";

    return {
        scanRoot:scanRoot,
        scanPath:scanPath
    };

    function scanPath( path ) {
        window.resolveLocalFileSystemURL(path, _gotFiles, errorHandler );
    }

    function scanRoot() {
        scanPath( root );
    }

function _gotFiles(entry) {
    // ? Check whether the entry is a file or a directory
    if (entry.isFile) {
        // * Handle file
        fileHandler( entry );
    }
    else {
        // * Scan directory and add media
        var dirReader = entry.createReader();
        dirReader.readEntries( function(entryList) {
            entryList.forEach( function ( entr ) {
                _gotFiles( entr );
            } );
        }, errorHandler );
    }
}

    function _defultFileHandler(fileEntry){
        console.log( "FileEntry: " + fileEntry.name + " | " + fileEntry.fullPath );
    }
    function _defultErrorHandler(error){
        console.log( 'File System Error: ' + error.code );
    }
};

<强>配置

  • <强> config.xml中
    删除偏好设置:偏好设置名称=&#34; AndroidExtraFilesystems&#34;

  • 确保测试环境可以在测试时访问它自己的外部存储。 (例如,如果你用usb连接它,确保它作为一个摄像头连接;在收到&#34; deviceready&#34;事件后调用API)

路径示例:
文件:///
文件:/// somefile /
文件:/// somefile
文件:///somefile/music/aaaaa.mp3