【问题标题】:Unable to Download file using flask with actual name无法使用具有实际名称的烧瓶下载文件
【发布时间】:2017-08-21 10:58:10
【问题描述】:

我正在尝试使用烧瓶下载文件。我的代码如下

@app.route('/Download')
def Down():
    rpm = request.args.get('rpm')
    root = '/home/rpmbuild/RPMS/'
    return send_from_directory(root,rpm)

文件名在 url 中传递。当我点击 url 时,我可以下载文件,但文件名总是在Download。我需要它是文件的实际名称。我也试过send_file(),但它也在以Download的名字下载它。

【问题讨论】:

    标签: python flask download sendfile


    【解决方案1】:

    send_from_directory的“选项”与sendfile相同:

    flask.send_file(filename_or_fp, mimetype=None, as_attachment=False,
                    attachment_filename=None, add_etags=True,
                    cache_timeout=None, conditional=False,
                    last_modified=None)

    所以你应该这样称呼它:

    @app.route('/Download')
    def Down():
        rpm = request.args.get('rpm')
        root = '/home/rpmbuild/RPMS/'
        return send_from_directory(root,rpm,attachment_filename='foo.ext')

    你当然可以用你想给文件命名的名字替换'foo.ext'。您可能还想将as_attachment 参数设置为True

    如果您想要同名,您可以使用os.path.basename(..)

    import os
    
    @app.route('/Download')
    def Down():
        rpm = request.args.get('rpm')
        root = '/home/rpmbuild/RPMS/'
        return send_from_directory(root,rpm,as_attachment=True,
                                   attachment_filename=os.path.basename(rpm))

    【讨论】:

      猜你喜欢
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 2018-09-16
      • 2019-02-10
      • 2015-12-24
      • 1970-01-01
      • 2017-06-09
      相关资源
      最近更新 更多