如何使用angularjs处理文件下载错误?

时间:2014-05-24 18:47:46

标签: javascript angularjs iframe download

下载文件看起来非常简单,并且有许多可行的解决方案。 工作直到服务器说401 UNAUTHORIZED我的要求很自然:

  • 在任何情况下都不能更换当前窗口。
  • 我不想打开一个新窗口,因为它毫无意义。
  • 如果出现错误,必须向用户显示一些消息。

我尝试使用iframe作为链接的目标,并希望在出现错误时收到通知。我觉得我天真。

  • 我可以设想在iframe中放置一些脚本来通知主页onunload。它看起来有点复杂,所以我先问一下。
  • 我可以向服务器询问结果。不管怎么说,这肯定会起作用。但它也很复杂,因为时间问题和会话已经过期,所以我不得不绕过这个。

2 个答案:

答案 0 :(得分:7)

您可以使用Blob对象从javascript触发文件下载。这是随File API引入的,仍处于 Working Draft 状态。 因此,您的浏览器支持有限。截至2015年,您对Blob URLsBlob 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

您还应该查看FileSaver.js,这也会回到data:URI

答案 1 :(得分:-1)

您可以通过使用HTTP拦截器来处理HTTP错误,而不会中断您的控制器/服务逻辑。发生错误时,在拦截器中处理它,然后将错误广播到错误处理程序,这可能会向用户显示错误。

$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
    return {
       'request': function(config) {
        // same as above
        },

        'response': function(response) {
        // same as above
     }
  };

});