【问题标题】:Phonegap Android write to sd cardPhonegap Android 写入 sd 卡
【发布时间】:2015-12-16 00:44:02
【问题描述】:

如果我在移动设备中使用 Phonegap Developer 进行测试,给出下面的代码,它会在我的 Nexus 5 设备的根目录中创建一个文件。

// create a file writer object
function CreateFileWriter()
{
    // request the file system object
window.requestFileSystem( LocalFileSystem.PERSISTENT, 0, OnFileSystemSuccess,fail);
}

function OnFileSystemSuccess( pFileSystemObj )
{
    console.log( pFileSystemObj.name );
    console.log( pFileSystemObj.root.name );

    pFileSystemObj.root.getFile( "file_name.txt", {create: true, exclusive: false}, OnFileGetSuccess, fail);
}

function OnFileGetSuccess( pFileEntryObj )
{
    pFileEntryObj.createWriter( function(pWriterObj){ 
    gWriterObj  = pWriterObj; 
    }, fail );
}

function fail(evt)
{
    console.log(evt.target.error.code);
}

但是,如果我部署应用程序并生成 apk。在我的设备中安装后。该文件不是在根目录下创建的。

我已在 AndroidManifest.xml 中授予权限并添加了文件插件。此外,从 gapdebug 调试。它没有显示任何错误。我假设该文件是在其他地方创建的。但我需要在 sdcard 或内存的根目录上写入文件。

请帮忙!

谢谢,

【问题讨论】:

  • 我认为你应该避免使用 HTML5 API,使用效果很好的Cordova File Plugin
  • 我使用的是 Cordova File Plugin 而不是 HTML5 API
  • 好的,但解析行应该类似于:window.resolveLocalFileSystemURL( cordova.file.dataDirectory + "myfile.dat", onSuccess, onError ); - 另一点:你是在 deviceready 事件中调用它吗?
  • 是的,正在调用 deviceready 事件。之后按钮出现。我已经在那个按钮中调用了这个。如果可能,请您展示一个示例。

标签: javascript android html cordova phonegap-build


【解决方案1】:

写文件示例:

var fileName = 'myfile.txt';    // your file name
var data = '...';               // your data, could be useful JSON.stringify to convert an object to JSON string
window.resolveLocalFileSystemURL( cordova.file.externalRootDirectory, function( directoryEntry ) {
    directoryEntry.getFile(fileName, { create: true }, function( fileEntry ) {
        fileEntry.createWriter( function( fileWriter ) {
            fileWriter.onwriteend = function( result ) {
                console.log( 'done.' );
            };
            fileWriter.onerror = function( error ) {
                console.log( error );
            };
            fileWriter.write( data );
        }, function( error ) { console.log( error ); } );
    }, function( error ) { console.log( error ); } );
}, function( error ) { console.log( error ); } );

【讨论】:

  • 你太棒了。一个星期以来我一直在寻找这个。再次感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-20
相关资源
最近更新 更多