[英]How to handle file download errors with angularjs?
下載文件看起來非常簡單,有許多工作解決方案。 工作直到服務器說401 UNAUTHORIZED
。 我的要求很自然:
我嘗試使用iframe
作為鏈接的目標,並希望在出現錯誤時收到通知。 我覺得我很天真。
onunload
。 它看起來有點復雜,所以我先問一下。 您可以使用Blob
對象從javascript觸發文件下載。 這是隨File API引入的,仍處於Working Draft狀態。 因此,您將獲得有限的瀏覽器支持。 截至2015年,您可以對Blob URL和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);
});
有一些庫可以擴展瀏覽器對Blob.js的支持
您還應該查看FileSaver.js ,它也回退到data:URI
。
您可以處理HTTP錯誤,而不會通過使用HTTP攔截器來中斷控制器/服務邏輯。 發生錯誤時,在攔截器中處理它,然后將錯誤廣播到錯誤處理程序,這可能會向用戶顯示錯誤。
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
// same as above
},
'response': function(response) {
// same as above
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.