Search code examples
ionic-frameworkngcordova

How to save images from server into device internal memory in ionic app?


I've tried with most of the cordova file related plugins and finally came up with this code. It's giving success message but they weren't appearing in gallery. Can anyone help with this, please ?

    $scope.download = function download(name, contentType, fileLInk) {
ionic.Platform.ready(function() {
  var url = apiServiceBaseUri + fileLInk;
  var targetPath = cordova.file.dataDirectory + 'myapp/' + name;
  var trustHosts = false;
  var options = {
    headers: {
      'Authorization': tokenType + ' ' + accessToken
    }
  };

  $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
    .then(function(result) {
      var alertPopup = $ionicPopup.alert({
        title: 'File has been downloaded',
      });
      $ionicListDelegate.closeOptionButtons();
    }, function(error) {
      $ionicListDelegate.closeOptionButtons();
      if (error.http_status == 401) {
        $ionicPopup.alert({
          title: 'Oops, Session is expired!',
          template: 'Looks like your session is expired or you logged in from someother device.'
        });
        $ionicHistory.clearCache().then(function() {
          $state.go('start.login');
        });
      }
      var alertPopup = $ionicPopup.alert({
        title: 'Sorry, something went wrong during the request!',
        template: error.data.errors[0].message
      });
    });
});
};

Solution

  • You should use this plugin after file-transfer

    cordova plugin add cordova-plugin-refresh-gallery
    

    and use this function in your success callbeck of file-transfer

    $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
        .then(function(result) {
         refreshMedia.refresh(targetPath); 
         //some other things 
    

    My Working Code

     $cordovaFileTransfer.download(url, targetPath, {}, true).then(function (result) {
                   refreshMedia.refresh(targetPath);
                   $scope.fullViewImageDownloadSpiner = false;
                   tostService.notify('Image Downloaded', 'top');
               }, function (error) {
                   $scope.fullViewImageDownloadSpiner = false;
                   tostService.notify('Try Again', 'top');
               }, function (progress) {
                   // PROGRESS HANDLING GOES HERE
                   //  $timeout(function () {
                   //     $scope.downloadProgress = (progress.loaded / progress.total) * 100;
                   // })
               });
    

    and Set your target path as

    var filename = url.split("/").pop();
    var targetPath = cordova.file.externalRootDirectory + '/Download/' + filename;
    

    This plugin updates the image gallery.When you save an image on android device, and image image is not showing up in gallery .This plugin will work

    Hope this solve your problem .. Thanks :)