+ * Created by Tomer on 2016-12-06.
+ angular.module('myApp.services.saveToGallery', [])
+ .factory("SaveToGalleryService", SaveToLibraryService);
+ SaveToLibraryService.$inject = ["$q"];
+ function SaveToLibraryService($q) {
+ 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) {
+ errorCallback("invalid arguments");
+ //checking Internet connection availablity
+ var networkState = navigator.connection.type;
+ if (networkState == Connection.NONE) {
+ errorCallback("not internet connection");
+ download(url, folderName, fileName)
+ .then(function onDlSuccess(fileEntry) {
+ refreshMedia.refresh(fileEntry.nativeURL);
+ successCallback(true, fileEntry);
+ }, function onDlError(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);
+ 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,
+ console.log("Download completed", entry);
+ //Download abort errors or download failed errors
+ console.log("download error source ", error);