如何使用angularjs处理文件下载错误? [英] How to handle file download errors with angularjs?

查看:97
本文介绍了如何使用angularjs处理文件下载错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Downloading files looks very trivial and there are many working solutions. Working until the server says 401 UNAUTHORIZED. My requirements are rather natural:


  • 在任何情况下都不能更换当前窗口。

  • 我不想打开新窗口,因为没有意义。

  • 如果出现错误,必须向用户显示一些消息。

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

I tried to use an iframe as a target of the link and hoped to be notified in case of an error. I see I was naive.


  • 我可以想象在iframe中放置一些脚本会通知主页 onunload 。它看起来有点复杂,所以我先问一下。

  • 我可以向服务器询问结果。不管怎么说,这肯定会起作用。但它也很复杂,因为时间问题而且会话已经过期,所以我必须绕过这个。

  • I could imagine to place some script in the iframe which would notify main page onunload. It look a bit complicated so I'm asking first instead.
  • I could ask the server about the outcome. This would surely work, somehow. But it's complicated too, as there's timing problem and the session is expired, so I'd have to circumvent this.

推荐答案

您可以使用 Blob 对象从javascript触发文件下载。这是随File API引入的,仍处于 Working Draft 状态。 所以你的浏览器支持有限。截至2015年,你有广泛的浏览器支持 Blob URL Blob构造函数

You can use a Blob object to trigger file download from javascript. This is introduced with the File API and still in Working Draft state. So you'll have limited browser-support. As of 2015, you have wide browser support for Blob URLs and 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

There are some libraries to extend browser support for this such as Blob.js

您还应该查看 FileSaver.js 也会回落到数据:URI

这篇关于如何使用angularjs处理文件下载错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆