1

Is it possible to trigger a download via a button and using AngularJS $http service in the background to provide the file?

I want to have a simple button, which starts a file download without opening a new window. Furthermore I have to set the Authorization inside of the header.

So far I did this:

var app = angular.module('myApp', []);


app.controller('myCtrl', function($scope, $http) {

  $scope.startDownload = function() {
    var auth = ""; //username + password
    $http.defaults.headers.common['Authorization'] = auth;

    //this will return a file
    $http({
      method: 'GET',
      url: 'https://upload.wikimedia.org/wikipedia/commons/1/1c/FuBK_testcard_vectorized.svg?download'/*,
      headers: {
        'Authorization': 'Basic efhjwefjfbweikabfkwhfb'
      }*/
    }).then(function(){
      //????
    });
  };

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <button type="button" ng-click="startDownload()">Download</button>
</div>
d4rty
  • 3,970
  • 5
  • 34
  • 73

2 Answers2

2

change this :

  ng-click="startDownload()"
  • I have corrected the typo. But it is still not working. I have updated the question and added an existing url to a picture file. The snippet is still not downloading the file on the users download folder. – d4rty Sep 12 '16 at 11:27
1

After reading a ton of questions regarding similar problems, it emphasizes that it is not possible to save a file on the users disk, which comes from an AJAX request.

See this question on Stackoverflow.

Community
  • 1
  • 1
d4rty
  • 3,970
  • 5
  • 34
  • 73