使用 bottle 下载文件时保留文件名 static_file

Retain filename while downloading a file with bottle static_file

我想要实现的是从 static_file 的路径下载文件(压缩日志文件夹)并保留原始文件名。这是我的代码:

@app.route('/logs')
def download_logs():
    filename = 'logs_' + time.strftime("%Y%m%d-%H%M%S")
    print(filename)
    shutil.make_archive(filename, 'zip', 'logs/')
    return static_file(filename + '.zip', './')

如您所见,我想将日志文件夹压缩到按日期和时间命名的存档并下载文件。下载的文件应使用与我在后端压缩的名称相同的名称下载。当前文件下载为 logs.zip,因此它获取路径名称。

使用download参数。这将强制浏览器显示下载对话框 - 在您的情况下,这是自动发生的,因为浏览器无法打开 zip 文件。但是如果你试图 "download" 例如这样一个HTML页面,会直接显示而不是下载

更重要的是,这允许您指定浏览器用于保存下载文件的文件名。在您的情况下,使用 static_file(filename + ".zip". "./", download=True) 就足够了,它使用原始文件名。或者,您可以使用 download="my.name.goes.here" 提供您自己的名称。看看 documentation 中的 'Forced Download'。