Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 220
shreyansh Avatar asked Jan 08 '23 23:01

shreyansh


1 Answers

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>
like image 127
Lesh_M Avatar answered Jan 31 '23 01:01

Lesh_M