4

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>
Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99
shreyansh
  • 1,637
  • 4
  • 26
  • 46
  • Create server side script which would send the image with content-disposition headers. Pretty simple stuff, just write/find online a script for your backend language. – dfsq Jul 14 '15 at 09:01
  • thanks for your response, Can you please share the link of some code to refer. – shreyansh Jul 14 '15 at 09:02
  • depends on your server side language. basically you just need to make GET request to your script (link link href). – dfsq Jul 14 '15 at 09:20

2 Answers2

6

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>
Lesh_M
  • 596
  • 8
  • 6
3

You can achieve this with the help of BLOB object

HTML

<body ng-app="myApp">
 <div  ng-controller="HomeCtrl">
<button ng-click="download()">download</button>
    <img id="photo"/>
</div>
</body>

Angular code:

angular.module('myApp', []);

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

  $scope.download=function()
  {
      $http.get('https://placeholdit.imgix.net/~text?txtsize=15&txt=image1&w=120&h=120', {responseType: "arraybuffer"}).success(function(data){

           var arrayBufferView = new Uint8Array( data );
    var blob = new Blob( [ arrayBufferView ], { type: "image/png" } );
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL( blob );
    var img = document.querySelector( "#photo" );
    img.src = imageUrl;
             // code to download image here
        }).error(function(err, status){})
  }



function SaveToDisk(fileURL, fileName) {
    // for non-IE
    if (!window.ActiveXObject) {
        var save = document.createElement('a');
        save.href = fileURL;
        save.target = '_blank';
        save.download = fileName || 'unknown';

        var event = document.createEvent('Event');
        event.initEvent('click', true, true);
        save.dispatchEvent(event);
        (window.URL || window.webkitURL).revokeObjectURL(save.href);
    }

    // for IE
    else if ( !! window.ActiveXObject && document.execCommand)     {
        var _window = window.open(fileURL, '_blank');
        _window.document.close();
        _window.document.execCommand('SaveAs', true, fileName || fileURL)
        _window.close();
    }
}
    }]);

Plunker for the solution:http://plnkr.co/edit/IKQKWkY6YMwodzpByx0f?p=preview New Pluncker Auto download: http://plnkr.co/edit/eevPO2fh3F37Yhvchnol?p=preview

Shubham Nigam
  • 3,844
  • 19
  • 32
  • Not a bad solution but I would put it in a directive so it's more reusable. Perhaps even as an attribute to the img tag that would create the button automatically – richbai90 Jul 14 '15 at 13:00
  • According to question, It satisfies the answer then you can it according to your convinience anywhere in the code ,check right icon or upvote if it helped you. – Shubham Nigam Jul 14 '15 at 13:07
  • It is just displaying the image , I want to download it automatically without right click and save option – shreyansh Jul 15 '15 at 03:31
  • Its working only for chrome not for mozilla and IE. See my requirements – shreyansh Jul 15 '15 at 11:12
  • You are using download attribute – shreyansh Jul 15 '15 at 11:15
  • i am running this code and it downloads the image but when i open it, the file has an error premature end of file encountered. Does anyone have a reason why i will b having this error – Kingsley Simon Oct 07 '15 at 10:26