如何使用angularjs点击按钮进入我们的本地下载图像?

时间:2015-07-14 08:56:08

标签: javascript angularjs angularjs-directive imagedownload

您好我是angularjs的新手,我在stackoverflow上看到了很多关于此问题的问题,但未能找到一个好的解决方案。

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

我的要求是 (1)我不想使用<a>标签

(2)我不想使用<download>属性,因为它应该在所有浏览器中都受支持。

当用户点击下载按钮时,图像应该下载到客户端的本地计算机上。

假设图像来自某个网​​址

<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>

1 个答案:

答案 0 :(得分:6)

&#13;
&#13;
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();
        })
    }
  }
]);
&#13;
<!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>
&#13;
&#13;
&#13;