shr*_*nsh 4 javascript imagedownload angularjs angularjs-directive
嗨,我是新手angularjs,我在stackoverflow上看到了很多关于此的问题,但未能找到一个好的解决方案.
<button ng-click="download()">download</button>
Run Code Online (Sandbox Code Playgroud)
我的要求是(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>
Run Code Online (Sandbox Code Playgroud)
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();
})
}
}
]);Run Code Online (Sandbox Code Playgroud)
<!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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17981 次 |
| 最近记录: |