【问题标题】:Offer a token protected file from flask using angular使用角度从烧瓶中提供令牌保护文件
【发布时间】:2015-06-03 16:08:14
【问题描述】:
  • 我有一个文件,与烧瓶一起提供,受基于令牌的保护 验证。
  • 我想提供一个 Angular 应用程序的下载
  • 令牌存储在 Angular 会话中,并放入每个 $http.get 或 post 的标头中

但是当我只是放置一个指向烧瓶路径的链接时,令牌不会添加到请求标头中,因为它不是有角度的 $http.get() 而只是一个普通的锚,我不能这样做(对吗?)。

我不想将 url 中的令牌作为查询字符串参数传递。 我如何向用户提供下载?我应该先将它 $http.get() 转换成 Angular,然后将其作为文件下载通过隧道吗?

登录后的令牌存储:

$window.sessionStorage.token = results.response.user.authentication_token;

在每个 $http get 或 post 中注入:

config.headers['Authentication-Token'] = $window.sessionStorage.getItem('token');

Flask(带有flask-security)部分:

@app.route("/download", methods=['GET'])
@auth_token_required
def download():
    response = make_response(open('filename.ext').read())
    response.headers["Content-Disposition"] = "attachment; filename=download.ext"
    return response

我该如何解决这个问题?

【问题讨论】:

  • 看看解决方案here。但仅适用于 HTML5。
  • 谢谢!这是一个很好的技巧,我会尽快写答案

标签: angularjs download flask token flask-security


【解决方案1】:

首先你通过 $http.get() 获取数据

然后我找到了两种方法:

  1. 将数据作为base64编码的数据插入到href属性中

  2. 将数据作为 javascript blob 插入,并在 href属性

第一种方法是由@Christian 在cmets 推荐的article 提出的。 我实现了它,您可以在下面找到代码。但是,该方法使较大文件(在这种情况下为 csv 文件)的 Chrome 崩溃,显然这是a limitation of chrome。 所以我会推荐方法2。

方法二

Angular(对于这种情况下的 csv 文件,为其他文件相应地更改类型:'text/csv':

$http.get('/downloadpath').
    success(function(downloadresult){
        fileData = new Blob([downloadresult], { type: 'text/csv' }); 
        fileUrl = URL.createObjectURL(fileData);
        $scope.download_href = fileUrl;
    });

HTML:

<a href="{{download_href}}" download="filename.ext">download</a>

烧瓶:

@app.route("/downloadpath", methods=['GET'])
@auth_token_required
def download():
    response = open('filename.ext','br').read()
    return response

为了完整起见,这里是方法 1:

方法一

 $http.get('/downloadpath').
    success(function(downloadresult){
        $scope.download_href = downloadresult;
    });

对于 html 也是一样的:

<a href="{{download_href}}" download="filename.ext">download</a>

Flask(例如 csv 文件,如果您有其他文件,请更改 'data:text/csv'):

@app.route("/downloadpath", methods=['GET'])
@auth_token_required
def download():
    encoded = base64.b64encode(open('export.csv','br').read())
    response = 'data:text/csv;base64,{}'.format(str(encoded, encoding='utf-8'))
    return response

两种方法的角度要求

您需要将方法 2 的 blob 协议和方法 1 的数据协议列入白名单:

var app = angular.module('myApp', []);

app.config( [
    '$compileProvider',
    function( $compileProvider )
    {   
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|data|blob):/);
    }
]);

【讨论】:

    猜你喜欢
    • 2020-11-14
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多