Showing posts with label cordova file system plugin. Show all posts
Showing posts with label cordova file system plugin. Show all posts

Thursday, 31 July 2014

Phonegap/Cordova: Download file

To download file in cordova you have to add following plugins:

1. File
2. File System
3. File Transfer

And example is here:
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, app.fileSystemSuccess, app.fileSystemFail);
        console.log('Received Event: ' + id);
    },

fileSystemSuccess: function(fileSystem) {
var directoryEntry = fileSystem.root;
directoryEntry.getDirectory("folder_rahul", {create: true, exclusive: false}, app.onDirectorySuccess, app.onDirectoryFail);
var rootdir = fileSystem.root;
var fp = rootdir.toURL();
alert(fp);
fp = fp + "folder_rahul/120px-State-lib-sum.png";
var fileTransfer = new FileTransfer();
   fileTransfer.download("http://data-gov.tw.rpi.edu/w/images/thumb/b/b1/State-lib-sum.png/120px-State-lib-sum.png",fp,
   function(entry) {
       alert("download complete: " + entry.fullPath);
   },
   function(error) {
cosnole.log(error);
       alert("download error source " + error.source);
       alert("download error target " + error.target);
       alert("upload error code" + error.code);
   }
);
},

fileSystemFail: function(evt) {
    alert("Failed---"+evt.target.error.code);
},

onDirectorySuccess: function(parent) {
console.log(parent);
},

onDirectoryFail: function(error) {
alert("Unable to create new directory: " + error.code);
}
};

More details are here and here