如何在离子应用程序中将图像从服务器保存到设备内部存储器?

时间:2016-10-05 11:54:07

标签: ionic-framework ngcordova

我尝试过与大多数与cordova文件相关的插件,最后想出了这段代码。这是成功的消息,但他们没有出现在画廊。有人可以帮帮忙吗?

    $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
      });
    });
});
};

1 个答案:

答案 0 :(得分:0)

您应该在文件传输后使用此插件

cordova plugin add cordova-plugin-refresh-gallery

并在文件传输的成功callbeck中使用此功能

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

我的工作代码

 $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;
               // })
           });

并将目标路径设置为

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

此插件更新图库。当您在Android设备上保存图像时,图像图像未显示在图库中。此插件可以使用

希望这能解决你的问题..谢谢:)