Snippets

Tomer Cagan Cordova/Phonegap save to gallery "service" - for Android devices

Created by Tomer Cagan
angular.module('myApp.controllers.whatever', [])
    .controller('WhateverController', function ($scope, SaveToGalleryService) {
    
    $scope.savePhoto = function(photoUrl, folderName, fileName, callback) {
        var fileName = new Date().getTime();
        SaveToGalleryService.saveToGallery(photoUrl, "Kiddiz.me", fileName, function (res) {
            console.log("Photo ", photoUrl, "photo saved", res);
            if (callback) {
                callback(true, res);
            }
        }, function () {
            console.log("Photo ", photoUrl, "failed to save photo");
            if (callback) {
                callback(false);
            }
        });
    }
});

// don't forget to include both the service and controller in your app.js file...
/**
 * Created by Tomer on 2016-12-06.
 */


(function() {
    angular.module('myApp.services.saveToGallery', [])
        .factory("SaveToGalleryService", SaveToLibraryService);

    SaveToLibraryService.$inject = ["$q"];

    function SaveToLibraryService($q) {
        return {
            saveToGallery: downloadFile
        };

        //First step check parameters mismatch and checking network connection if available call    download function
        function downloadFile(url, folderName, fileName, successCallback, errorCallback) {
            //Parameters mismatch check
            if (!url || !folderName || !fileName) {
                if (errorCallback) {
                    errorCallback("invalid arguments");
                }
            }
            else {
                //checking Internet connection availablity
                var networkState = navigator.connection.type;
                if (networkState == Connection.NONE) {
                    if (errorCallback) {
                        errorCallback("not internet connection");
                    }
                } else {
                    download(url, folderName, fileName)
                        .then(function onDlSuccess(fileEntry) {
                            refreshMedia.refresh(fileEntry.nativeURL);
                            if (successCallback) {
                                successCallback(true, fileEntry);
                            }
                        }, function onDlError(err) {
                            if (errorCallback) {
                                errorCallback(err);
                            }
                        });
                }
            }
        }

        function download(url, folderName, fileName) {
            var defer = $q.defer();

            var downloadLink = encodeURI(url),
                ext = downloadLink.substr(downloadLink.lastIndexOf('.') + 1); //Get extension of URL

            //step to request a file system
            window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, fileSystemSuccess, fileSystemFail);

            function fileSystemSuccess(dir) {
                console.log("fileSystemSuccess", dir);
                dir.getDirectory(folderName, { create: true, exclusive: false }, onDirectorySuccess, onDirectoryFail);
            }

            function fileSystemFail(evt) {
                //Unable to access file system
                console.log("fileSystemFail", evt.target.error.code);
                defer.reject(evt.target.error);
            }

            function onDirectorySuccess(dir) {
                console.log("onDirectorySuccess", dir);
                var fp = dir.toURL(); // Returns fill path of local directory

                fp = fp + "/" + fileName + "." + ext; // fullpath and name of the file which we want to give
                // download function call
                filetransfer(downloadLink, fp);
            }

            function onDirectoryFail(error) {
                //Error while creating directory
                console.log("onDirectoryFail", error);
                defer.reject(error);
            }

            function filetransfer(downloadLink, fp) {
                console.log("starting file transfer", downloadLink, "-->", fp);

                var fileTransfer = new FileTransfer();
                // File download function with URL and local path
                fileTransfer.download(downloadLink, fp,
                    function (entry) {
                        console.log("Download completed", entry);
                        defer.resolve(entry);
                    },
                    function (error) {
                        //Download abort errors or download failed errors
                        console.log("download error source ", error);
                        defer.reject(error);
                    }
                );
            }

            return defer.promise;
        }
    }
})();

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.