无法使用具有实际名称的烧瓶下载文件

Unable to Download file using flask with actual name

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

@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.

send_from_directory are the same as sendfile"options":

flask.send_file(filename_or_fp, mimetype=None, as_attachment=False,
                <b>attachment_filename=None</b>, 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,<b>attachment_filename='foo.ext'</b>)

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

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

<b>import os</b>

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