如何使用phonegap从android下载URL文件?

时间:2012-08-30 11:04:40

标签: javascript android html5 cordova download

我想从URL下载文件。如果我点击下载按钮,文件网址应该连接,它应该被下载到手机内存或Android的SD卡中。

有谁能帮助我如何使用phonegap让它工作?

谢谢。

1 个答案:

答案 0 :(得分:0)

请使用Phonegap或CoreDova中的FileTransfer API。以下是来自同一来源的示例代码:

var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");

fileTransfer.download(
    uri,
    filePath,
    function(entry) {
        console.log("download complete: " + entry.fullPath);
    },
    function(error) {
        console.log("download error source " + error.source);
        console.log("download error target " + error.target);
        console.log("upload error code" + error.code);
    }
);

要将文件保存在SDCard上,请使用FileWriter

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);
}