下载文件看起来很简单,并且有许多可行的解决方案。一直工作到服务器说401 UNAUTHORIZED
为止。我的要求很自然:
我尝试将
iframe
用作链接的目标,并希望在发生错误时得到通知。我看我很天真。onunload
。看起来有点复杂,所以我先问一下。 最佳答案
您可以使用 Blob
对象触发从javascript下载文件。这是通过File API引入的,并且仍处于“工作草稿”状态。因此,您将获得有限的浏览器支持。截至2015年,您已经对Blob URLs和Blob Constructor拥有广泛的浏览器支持。
<div ng-controller="appController" ng-app="app">
<a ng-href="{{ fileUrl }}" download="file.txt">download</a>
</div>
var app = angular.module('app', []);
// Angular prepends "unsafe" tag in ng-href to prevent XSS
// so we need to sanitize this
app.config(['$compileProvider', function ($compileProvider) {
// for Angular 1.0.x and 1.1.x, you should use urlSanitizationWhitelist
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob|ftp):/);
}]);
app.controller('appController', function ($scope, $window) {
// Creating a Blob with our data for download
// this will parse the URL in ng-href such as: blob:http...
var data = 'some data here...',
blob = new Blob([data], { type: 'text/plain' }),
url = $window.URL || $window.webkitURL;
$scope.fileUrl = url.createObjectURL(blob);
});
看到一个demo fiddle here。
有一些库可以扩展浏览器对此的支持,例如Blob.js
您还应该 checkout FileSaver.js,它也回落到
data:URI
。关于javascript - 如何使用angularjs处理文件下载错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23848522/