Android 如何使用cordova文件/文件系统根插件访问外部存储?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22868089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access external storage with cordova file / file-system-roots plugins?
提问by Andi
Problem description:I can access the internal storage with either the file or the file-system-roots (read and write). But such a file can not be access from an other app. For example if I want to send this file through the emailComposerPlugin, the file can not be accessed by the email client. (Same goes for the "open with" function.)
If I change the options {sandboxed: true}
to false (to write to the external storage), it does not work and ends up in a FileUtils.UNKNOWN_ERR. I tried the application while the phone disconnected from USB, as some docs mentioned that external storage can not be accessed while mounted on the pc - same result though.
问题描述:我可以使用文件或文件系统根(读写)访问内部存储。但是这样的文件不能从其他应用程序访问。例如,如果我想通过 emailComposerPlugin 发送此文件,则电子邮件客户端无法访问该文件。(“打开方式”功能也是如此。)如果我将选项更改{sandboxed: true}
为 false(写入外部存储),它将不起作用并以 FileUtils.UNKNOWN_ERR 结束。我在手机与 USB 断开连接时尝试了该应用程序,因为一些文档提到安装在 PC 上时无法访问外部存储 - 但结果相同。
From what I read on the mailing listthis should be possible. It seems I miss a crucial point?
从我在邮件列表上读到的内容来看,这应该是可能的。似乎我错过了一个关键点?
Context:I try to enable an hybrid application created for iPhone to run on android devices. To have a little playground, I create a small test project.
上下文:我尝试启用为 iPhone 创建的混合应用程序以在 android 设备上运行。为了有一个小操场,我创建了一个小测试项目。
Edit:There seems to be a problem between file-system-roots and file plugin. But I have the newest versions of both of them. (File: 1.0.1 File-system-roots: 0.1.0) Debugging the file-system and file classes show that
编辑:文件系统根目录和文件插件之间似乎存在问题。但我有他们两个的最新版本。(File: 1.0.1 File-system-roots: 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
What have I tried?
我尝试了什么?
config.xml
配置文件
<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external" />
AndroidManifest.xml
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
javascript code
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
}
}
回答by Andi
After digging this whole topic quite a bit, i figured out:
在深入研究了整个主题之后,我想出了:
- There is no need for the file system roots plugin.
- There is more configuration needed in config.xml.
- You need to use not the standard FileApi way, but the following to access the files.
- 不需要文件系统根插件。
- config.xml 中需要更多配置。
- 您不需要使用标准的 FileApi 方式,而是使用以下方式来访问文件。
JavaScript usage:
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
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
回答by Faker
After hours of struggling, finally I'm able to scan sdcard and gain access to the files by providing a directory like "files://pathtofile/".
I've submit an API and a sample project
https://github.com/xjxxjx1017/cordova-phonegap-android-sdcard-full-external-storage-access-library
经过数小时的努力,我终于能够通过提供“files://pathtofile/”之类的目录来扫描sdcard并访问文件。
我已经提交了一个 API 和一个示例项目
https://github.com/xjxxjx1017/cordova-phonegap-android-sdcard-full-external-storage-access-library
Example of using the API
使用 API 的示例
new ExternalStorageSdcardAccess( fileHandler ).scanPath( "file:///storage/sdcard1/music" );
function fileHandler( fileEntry ) {
console.log( fileEntry.name + " | " + fileEntry.toURL() );
}
The API source code
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 );
}
};
Configurations
配置
config.xml
delete preference:preference name="AndroidExtraFilesystems"make sure testing environment can accessit's own external storage at the time of testing. ( e.p. if you connect it with usb, make sure it is connected as a camera; Call the APIs after recieving the "deviceready" event )
config.xml
删除首选项:首选项名称="AndroidExtraFilesystems"确保测试环境在测试时可以访问它自己的外部存储。( ep 如果你用usb连接,确保它作为相机连接;在收到“deviceready”事件后调用API)
Path example:
file:///
file:///somefile/
file:///somefile
file:///somefile/music/aaaaa.mp3
路径示例:
file:///
file:///somefile/
file:///somefile
file:///somefile/music/aaaaa.mp3