j7nn7k
j7nn7k

Reputation: 18582

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

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

Upvotes: 43

Views: 96425

Answers (6)

Flavio Lacerda
Flavio Lacerda

Reputation: 29

Updated Answer for new Cordova

function downloadFile(url, filename, callback, callback_error) {
    var fileTransfer = new FileTransfer();
    fileTransfer.download(url,
        cordova.file.dataDirectory + "cache/" + filename,
        function (theFile) {
            console.log("download complete: " + theFile.toURL());
            if (callback)
                callback();
        },
        function (error) {
            console.log("download error source " + error.source);
            console.log("download error target " + error.target);
            console.log("upload error code: " + error.code);
            if (callback_error)
                callback_error();
        }
    );
}

Upvotes: 2

Adarsh V C
Adarsh V C

Reputation: 2314

For downloading and displaying a file, follow the sample code.

Include the given code just above the </head> tag in your index.html

< script type = "text/javascript" charset = "utf-8" >
  // Wait for Cordova to load
  document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
  alert("Going to start download");
  downloadFile();
}

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

function showLink(url) {
  alert(url);
  var divEl = document.getElementById("deviceready");
  var aElem = document.createElement("a");
  aElem.setAttribute("target", "_blank");
  aElem.setAttribute("href", url);
  aElem.appendChild(document.createTextNode("Ready! Click To Open."))
  divEl.appendChild(aElem);
}

function fail(evt) {
  console.log(evt.target.error.code);
}
</script>

Refer :- Blog Post

Upvotes: 0

Jorge Torres
Jorge Torres

Reputation: 269

You can do this in one line of code:

new FileManager().download_file('http://url','target_path',Log('downloaded success'));

target_path: can include directory (example: dira/dirb/file.html) and the directories will be created recursively.

You can find the library to do this here:

https://github.com/torrmal/cordova-simplefilemanagement

Upvotes: 8

justmoon
justmoon

Reputation: 1311

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

Upvotes: 93

j7nn7k
j7nn7k

Reputation: 18582

This is how I solved it. First set the file paths, wich are different for Android and iOS

var file_path;
function setFilePath() {
    if(detectAndroid()) {   
        file_path = "file:///android_asset/www/res/db/";
        //4 Android
    } else {
        file_path = "res//db//";
        //4 apache//iOS/desktop
    }
}

Then I load my JSON files, wich are prepackaged with the app, into the local browser storage. Like this:

localStorage["my_json_data"] = loadJSON(file_path + "my_json_data.json");

function loadJSON(url) {
    return jQuery.ajax({
        url : url,
        async : false,
        dataType : 'json'
    }).responseText;
}

If I wanna update my data. I get the new JSON Data from the server and push it into the local storage. If the server is on a different domain, which is the case most of the time, you have to make a JSONP call (check jQuery's docs on JSONP). I did it kinda like this:

$.getJSON(my_host + 'json.php?function=' + my_json_function + '&callback=?', function (json_data) {
    //write to local storage
    localStorage["my_json_data"] = JSON.stringify(json_data);

});

Upvotes: 24

avoision
avoision

Reputation: 1235

My suggestion would be to look into PhoneGap's File API. I haven't used it myself, but it should do what you're after.

Upvotes: 2

Related Questions