Download files and store them locally with Phonegap/jQuery Mobile Android and iOS Apps

j7nn7k picture j7nn7k · Jun 20, 2011 · Viewed 95.3k times · Source

I wrote an jQuery Mobile app and packaged it with Phonegap to iOS and Android apps.

At this point I am using locally stored json files to read data.

I would like to update these json files from time to time by downloading newer json files from a server.

How can I get the json from the server and store the json files to the local file system of Android and iOS?

Cheers Johe

Answer

justmoon picture justmoon · Mar 30, 2012

Use FileTransfer.download, here is an example:

function downloadFile(){

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, 
    function onFileSystemSuccess(fileSystem) {
        fileSystem.root.getFile(
        "dummy.html", {create: true, exclusive: false}, 
        function gotFileEntry(fileEntry) {
            var sPath = fileEntry.fullPath.replace("dummy.html","");
            var fileTransfer = new FileTransfer();
            fileEntry.remove();

            fileTransfer.download(
                "http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
                sPath + "theFile.pdf",
                function(theFile) {
                    console.log("download complete: " + theFile.toURI());
                    showLink(theFile.toURI());
                },
                function(error) {
                    console.log("download error source " + error.source);
                    console.log("download error target " + error.target);
                    console.log("upload error code: " + error.code);
                }
            );
        }, fail);
    }, fail);
};
}