How to download an image by clicking on button into our local using angularjs?

shreyansh picture shreyansh · Jul 14, 2015 · Viewed 21.2k times · Source

Hi I am new to angularjs and I saw a lot of questions on stackoverflow regarding this, but was not able to find a good solution.

<button ng-click="download()">download</button>

My requirement is (1) I don't want to use <a> tag

(2) I don't want to use <download> attribute, because it should be supported in all browsers.

When user clicks on download button the image should get downloaded to client's local machine.

Assume the image is coming from some url

<script>
angular.module('myApp', []);

angular.module('myApp').controller('HomeCtrl', ['$scope', '$http', function($scope, $http) {

  $scope.download=function()
  {
      $http.get(url).success(function(data){
             // code to download image here
        }).error(function(err, status){})
  }

}]);
</script>

Answer

Omer Leshem picture Omer Leshem · Aug 30, 2016

angular.module('myApp', []).controller('HomeCtrl', ['$scope', '$http',
  function($scope, $http) {
    $scope.download = function() {
      $http.get('https://unsplash.it/200/300', {
          responseType: "arraybuffer"
        })
        .success(function(data) {
          var anchor = angular.element('<a/>');
          var blob = new Blob([data]);
          anchor.attr({
            href: window.URL.createObjectURL(blob),
            target: '_blank',
            download: 'fileName.png'
          })[0].click();
        })
    }
  }
]);
<!doctype html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="myApp">
  <div ng-controller="HomeCtrl">
    <button ng-click="download()">download</button>
  </div>
</body>
</html>