Ekta Shukla
Ekta Shukla

Reputation: 480

Downloading pdf file in SD card using Phone Gap in android

I want to download pdf file in my android phone using phone gap.can any one help me to download it? i have used https://github.com/phonegap/phonegap-plugins/tree/master/Android/Downloader plugin but it is not working.If anybody have any other downloading method then please let me know.. Thanks in advance..

Upvotes: 1

Views: 5925

Answers (2)

NuuoeiZ
NuuoeiZ

Reputation: 94

** You must add plugin file API, file transfer in phonegap (3.0+)

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

in Link

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

Upvotes: 0

dhaval
dhaval

Reputation: 7659

You can use the phonegap file api to download the files you want from server. Check docs for more detail - FileTransfer API

Here is an example code to download and save a pdf file in your sdcard.

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

For full source - https://gist.github.com/3055240

Upvotes: 4

Related Questions