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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With