当用户按下“下载”按钮时,我正在试图找出如何允许用户下载包含多个图像的文件夹。目前,我只能使用send_file代码来允许用户下载单个图像。有什么办法可以做到吗?
@app.route('/download')
def download():
path = "where my image is"
return send_file(path, as_attachment=True)
这是我的当前代码,我想要修改它。
发布于 2021-10-11 17:38:28
我建议你把目录归档,然后发送。
创建文件夹中所有文件的列表。
然后将这些文件压缩到压缩到流的zip存档中。
然后通过send_file传输该流。
from flask import send_file
from zipfile import ZipFile
from io import BytesIO
import os, glob
@app.route('/download', methods=['GET'])
def download():
path = # target directory
root = os.path.dirname(path)
files = glob.glob(os.path.join(path, '*'))
stream = BytesIO()
with ZipFile(stream, 'w') as zf:
for f in files:
zf.write(f, os.path.relpath(f, root))
stream.seek(0)
return send_file(
stream,
as_attachment=True,
attachment_filename='archive.zip',
mimetype='application/zip'
)
https://stackoverflow.com/questions/69533329
复制