在android上使用Cordova将文件写入外部(虚拟)存储
我正在尝试使用Cordova写入android平板电脑的外部存储(虚拟SD)。事实上,我正在尝试访问由“bitwebserver”(android的LAMP)创建的“www”目录 我有下面的代码 但我无法创建该文件,我得到的是5或9错误代码 我错过了什么 谢谢在android上使用Cordova将文件写入外部(虚拟)存储,android,cordova,cordova-plugins,Android,Cordova,Cordova Plugins,我正在尝试使用Cordova写入android平板电脑的外部存储(虚拟SD)。事实上,我正在尝试访问由“bitwebserver”(android的LAMP)创建的“www”目录 我有下面的代码 但我无法创建该文件,我得到的是5或9错误代码 我错过了什么 谢谢 <script> // Wait for Cordova to load document.addEventListener("deviceready", onDeviceReady, false);
<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>
//等待Cordova加载
文件。添加的监听器(“deviceready”,OnDeviceraddy,false);
//我们准备好了
函数ondevicerady(){
requestFileSystem(LocalFileSystem.PERSISTENT,0,gotFileSystem,fail);
}
功能文件系统(文件系统){
fileSystem.root.getFile(cordova.file.externalRootDirectory+“/www/test.txt”{
创造:真的,
独家:假
},gotFileEntry,失败);
}
函数gotFileEntry(fileEntry){
createWriter(gotFileWriter,失败);
}
函数gotFileWriter(writer){
writer.onwriteend=函数(evt){
log(“文件内容现在是‘一些示例文本’”);
writer.truncate(11);
writer.onwriteend=函数(evt){
log(“文件内容现在是‘一些示例’”);
作者:seek(4);
写(“不同的文本”);
writer.onwriteend=函数(evt){
log(“文件内容现在是‘一些不同的文本’”);
}
};
};
writer.write(“一些示例文本”);
}
功能失败(错误){
console.log(错误代码);
console.log(错误);
}
在我看来,您的问题在于您试图在应用程序沙箱之外的位置写入模拟SD卡
自Android 4.4以来,SD卡根目录(/sdcard/
,/storage/emulated/0
)是只读的,因此您无法对其进行写入。这同样适用于应用程序沙箱区域之外的任何其他文件夹。
试图写入未经授权的区域将导致调用writer.onerror()
函数,错误代码为9:不允许修改\u ERR
。
因此,尝试写入cordova.file.externalRootDirectory+“/www/test.txt”
将解析为/sdcard/www/test.txt
,并导致上述错误
您必须写入SD卡上的应用程序存储目录(例如/sdcard/Android/data/your.app.package.id/
)。
您可以使用cordova插件文件
作为cordova.file.externalApplicationStorageDirectory
引用此位置
有关不同版本Android中SD卡访问的详细信息,请参阅