Search code examples
javascriptangularjscordovaionic-frameworkcordova-plugins

CordovaFileTransfer | How put string from the headers to TargetPath?


I have project write with Ionic Framework and AngularJS. His task is to download files from the URL, type as http://www.uzhnu.edu.ua/uk/infocentre/get/6500 The problem is that the examples of "how to download the file and give it a name" is only if the path to URL line have his name .

The name of my file does not have this name in url. It is in the headers of http request, here is screen made with POSTMAN, but how to get it and put in a variable TargetPath, I do not know. Can anyone suggest something? Here is code of

FileTransferController.js:

app.controller('MyCtrl', function($scope, $cordovaFile, $cordovaDialogs, $window, $ionicLoading,$ionicPopup, $timeout, $cordovaFileTransfer) {

  $scope.id = '6500';

  $scope.downloadFile = function() {
    $ionicLoading.show({template: 'Download file...'});
    var url = "http://www.uzhnu.edu.ua/uk/infocentre/get/"+$scope.id;
    var filename = $scope.id+".doc";
    alert(filename);
    var targetPath = "/storage/sdcard0/documents/" + filename;
    var trustHosts = true;
    var options = {};
    $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
      .then(function(entry) {
          // Success!
          $ionicLoading.hide();
          console.log('download complete: ' + entry.toURL());
          alert('File download: ' + targetPath);
        }, function(error) {
          $ionicLoading.hide();
          // An error occured. Show a message to the user
          alert('Sorry');
          alert(JSON.stringify(error));
          console.log("download error source " + error.source);
          console.log("download error target " + error.target);
          console.log("upload error code" + error.code);
        },
        false,
        {
          headers: {
            "Content-Disposition": ""
          },
        });
  };
});

app.js:

var app = angular.module('starter', ['ionic', 'ngCordova'])
  .run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
      if(window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      }
      if(window.StatusBar) {
        StatusBar.styleDefault();
      }
    });
  })

Index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
  <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
  <title></title>

  <link href="lib/ionic/css/ionic.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">
  <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
  <link href="css/ionic.app.css" rel="stylesheet">
  -->
  <!-- ionic/angularjs js -->
  <script src="lib/ionic/js/ionic.bundle.js"></script>
  <!-- ng-cordova  -->
  <script src="js/ng-cordova.js"></script>
  <script src="js/ng-cordova.js"></script>
  <script src="js/ng-cordova.min.js"></script>
  <!-- cordova script (this will be a 404 during development) -->
  <script src="cordova.js"></script>
  <!-- your app's js -->
  <script src="js/app.js"></script>
  <script src="js/FileTransferController.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
  <ion-header-bar class="bar-stable">
    <h1 class="title">Ionic Blank Starter</h1>
  </ion-header-bar>
  <ion-content ng-controller="MyCtrl">
    <button class="button-positive" ng-click="downloadFile()">Download File</button>
  </ion-content>
</ion-pane>
</body>
</html>

P.S. Code work only on real device. And must download all plugins:

ionic plugin add cordova-plugin-file

ionic plugin add cordova-plugin-file-transfer

and in folder "js" add file "ng-cordova.js" and "ng-cordova.min.js". DOwnload they can with:

bower install ngCordova


Solution

  • YES! Finally I did it!If someone will need a code, her ir is:

     $scope.downloadFile = function() {
        var url = "http://example.com/page";
        $ionicLoading.show({template: 'Download file...'});
        $http.get(url).
          success(function (data, status, headers) {
            var head = headers('Content-Disposition');
            var filename = head.substr(head.lastIndexOf('=')+1);
            alert(filename);
            var targetPath = "/storage/sdcard0/documents/" + filename;
            var trustHosts = true;
            var options = {};
            $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
              .then(function(entry) {
                $ionicLoading.hide();
                console.log('download complete: ' + entry.toURL());
                alert('File download: ' + targetPath);
              }, function(error) {
                $ionicLoading.hide();
                console.log('headers: ' + headers('Cache-Control'));
                // An error occured. Show a message to the user
                alert('Sorry');
                alert(JSON.stringify(error));
              })
            alert(head1);
            $ionicLoading.hide();
            $scope.$broadcast('scroll.refreshComplete');
            return(JSON.stringify(head1))
          })
          .error(function (status) {
            alert(status);
            $ionicLoading.hide();
            $scope.$broadcast('scroll.refreshComplete');
          });
      };