Search code examples
angularjsionic-frameworkcordova-pluginsngcordova

CordovaFile & CordovaFileTransfer. How get correct name of file, with correct type file


I have a project that loads the files from site. In the browser, click a link (http://www.uzhnu.edu.ua/uk/infocentre/get/6500), it loads files at once with сorrectly name and extension. How to implement it in the ionic app, I do not know. File downloaded from url, where $scope.id is id of file (etc. 6500) Help me please, or give some ideas how solve this.

$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() {
// Success!
$ionicLoading.hide();
alert('File download ' + targetPath);
}, function(error) {
$ionicLoading.hide();
// An error occured. Show a message to the user
alert('Sorry');
alert(JSON.stringify(error));
});
};

Solution

  • YES! Finally I did it!If someone will need a code, here it 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');
          });
      };