Download files and store them locally with Phonegap/jQuery Mobile Android and iOS Apps
Solution 1
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);
});
Solution 2
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);
};
}
Solution 3
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
Solution 4
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.
Solution 5
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();
}
);
}
Related videos on Youtube
j7nn7k
Hi, I'm Jannik, Entrepreneur and coder. Combining both in my current position as founder & CTO of Particulate. I studied at the University of Koblenz, Germany (MSc of Business and Computer Science). I'm interesed in technology, traveling, football and music
Updated on February 22, 2020Comments
-
j7nn7k about 4 years
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
-
Eshwar Chaitanya over 10 yearsWe are fetching the data as string,then store in to byte array to form as pdf.I would be very glad if you can provide me the code snippet for saving the generated pdf in iPad,then viewing the same.Banging our heads since weeks to find a way for this.Although we were able to do with android,but not for ios :(
-
-
j7nn7k almost 13 yearsI tried the file api but I could not make it work. Sample code anyone?
-
raym0nd over 12 years@JoheGreen did you solve your problem? can you post sample code of how you did it ?
-
j7nn7k about 12 yearsYes it does if you write/use an xml parser.
-
Blowsie over 11 yearsThis is a bad approach as it uses both async:false and cross domain requests. You should be using phonegaps FileTransfer.download instead docs.phonegap.com/en/2.0.0/…
-
Mark Verkiel over 11 yearsI agree with @Blowsie since you are working with a framework that implemented this functionality, you shouldn't have to do workarounds.
-
dreamerkumar almost 11 yearsThank you for this amazing piece of code. It had everything I needed .. well except for that fail variable refereneced at the end. If you are planning to use this just define fail as a function like: function fail(error) { console.log(error.code); }
-
Lali Pali almost 11 yearsDo you suggest to use the File API to make ajax calls with phonegap, I have been trying a while to understand, but is first time I see someone suggesting not using jQuery? Can you explain a little bit more please?
-
beNerd over 10 yearshow do i force it not to use external storage and store it in abc folder created under www directory?
-
tayler about 10 yearsThe above code was originally posted here: gist.github.com/nathanpc/2464060 as you can see a couple of extra functions (fail and showLink) are needed to make the code functional.
-
shashwat about 10 yearswhat is dummy.html here..??
-
Pahlevi Fikri Auliya almost 10 years^+1, why you remove fileEntry?
-
tarikakyol almost 10 yearsdummy.html is created to find out what full path is.
-
h0mayun over 9 yearsIn new version of transfer plugin use fileEntry.toURL().replace("dummy.html","");
-
shmuli over 9 years@justmoon: Where does this download to? Path?
-
Stranger about 9 yearsThis code won't work anymore with the newer version of Cordova API. They changed it a bit, see this topic - stackoverflow.com/questions/21756274/… Also, creating dummy is not really necessary, you can just go with fileSystem.root.toNativeURL()