Download and Store External Files to Mobile in PhoneGap

23 / Sep / 2012 by Uday Pratap Singh 7 comments

In my current PhoneGap project, I was required to give the offline support of the application. I had to store all the external files on the device and refer the file from local device path. This required a thorough knowledge of storing external files on a device using PhoneGap.
PhoneGap comes with very handy FileTransfer API which allows a developer to download any file from URL and store it on the device. For storage, we needed the complete path where we wanted to store the file. Let’s take an example.

[java]
function storeIntelligrapeLogo(){
var url = "http://www.intelligrape.com/images/logo.png"; // image url
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
var imagePath = fs.root.fullPath + "/logo.png"; // full file path
var fileTransfer = new FileTransfer();
fileTransfer.download(url, imagePath, function (entry) {
console.log(entry.fullPath); // entry is fileEntry object
}, function (error) {
console.log("Some error");
});
})
}
[/java]

Using above code, we were able to download the file and its stored in “/Users/intelligrape/Library/Application Support/iPhone Simulator/5.0/Applications/CF2A9018-49B9-4DE6-91FC-EA76CB435FC8/Documents/logo.png” on my system (As I run the code on simulator).

FOUND THIS USEFUL? SHARE IT

comments (7)

  1. Dinesh

    We tried the sample code above but it only works for Android & not iOS or Windows phones. We put in file storage path for iOS but download is not working. Please advise!

    Reply
  2. Harsh

    The above code is not working in phonegap for android. What are the changes that need to be done and where the file will be stored after downloading.
    Thanks in advance.

    Reply
  3. Vin

    As far as I’m aware, you cannot store non-user-generated content into the ~/Documents/ folder of your app. Apple will reject your app if it does this.

    Files that can be regenerated and/or downloaded again, cannot reside in the ~/Documents folder, unless you flag them as files that do not get backupped to iCloud (which is possible, if you are not handling dynamic content that needs to be available offline, in which case you could also just add them to your App assets).

    Other option is to store the content into the ~/Library/Caches folder, which is ok.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *