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

maa*_*nus 5 javascript iframe download angularjs

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

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

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

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

Onu*_*rım 7

您可以使用Blob对象从javascript触发文件下载.这是随File API引入的,仍处于Working Draft状态.因此,您将获得有限的浏览器支持.截至2015年,您可以对Blob URLBlob Constructor提供广泛的浏览器支持.

<div ng-controller="appController" ng-app="app">
    <a ng-href="{{ fileUrl }}" download="file.txt">download</a>
</div>
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)

在这里看一个演示小提琴.

有一些库可以扩展浏览器对Blob.js的支持

您还应该查看FileSaver.js,它也可以追溯到data:URI.