使用android中的Phone Gap在SD卡中下载pdf文件

时间:2012-07-05 13:12:56

标签: android cordova

我想使用手机gap.c在我的Android手机中下载pdf文件。任何人都可以帮我下载吗?我使用了https://github.com/phonegap/phonegap-plugins/tree/master/Android/Downloader插件,但它没有用。如果有人有任何其他下载方法,请告诉我.. 提前谢谢..

2 个答案:

答案 0 :(得分:4)

您可以使用phonegap文件api从服务器下载所需的文件。查看文档以获取更多详细信息 - FileTransfer API

以下是在SD卡中下载和保存pdf文件的示例代码。

window.appRootDirName = "download_test";
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    console.log("device is ready");
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function fail() {
    console.log("failed to get filesystem");
}

function gotFS(fileSystem) {
    console.log("filesystem got");
    window.fileSystem = fileSystem;
    fileSystem.root.getDirectory(window.appRootDirName, {
        create : true,
        exclusive : false
    }, dirReady, fail);
}

function dirReady(entry) {
    window.appRootDir = entry;
    console.log("application dir is ready");
}


downloadFile = function(){
    var fileTransfer = new FileTransfer();

    var url = "http://www.irs.gov/pub/irs-pdf/fw4.pdf";
    var filePath = window.appRootDir.fullPath + "/test.pdf";

    fileTransfer.download(
        url,
        filePath,
        function(entry) {
            alert("download complete: " + entry.fullPath);
        },
        function(error) {
            alert("download error" + error.source);
        }
    );
}

完整来源 - https://gist.github.com/3055240

答案 1 :(得分:0)

**你必须在phonegap(3.0 +)中添加插件文件API,文件传输

function downloadPDF(url, fileName, folder) {
    var fileTransfer = new FileTransfer();
    var uri = encodeURI(url);
    var fileURL = folder + fileName;

    fileTransfer.download(
        uri,
        fileURL,
        function(entry) {
            alert("complete");
            console.log("download complete: " + entry.toURL());
        },
        function(error) {
            alert("upload error code" + error.code);
            console.log("download error source " + error.source);
            console.log("download error target " + error.target);
            console.log("upload error code" + error.code);
        },
        false,
        {
            headers: {
                "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
            }
        }
    );
}
链接

中的

<a href="#" 
    onclick="
    downloadPDF(
        'http://cran.r-project.org/doc/manuals/R-intro.pdf',
        'R-intro.pdf',
        '/sdcard/nuuoeiz/'
    );">
    Download PDF</a>