用浏览器压缩下载一个临时文件夹

Compress and download a temporary folder with a browser

有没有办法将包含文件和文件夹的临时文件夹(如 folder1)压缩成一个 zip 文件并在浏览器中启动该 zip 文件的下载?

import tempfile
import os

folder1 = tempfile.mkdtemp(prefix="myapplication")
folder2 = tempfile.mkdtemp(prefix=f"{folder1}/two")
with os.fdopen(f"{folder2}/test.txt", 'w+') as tmp1:
        tmp1.write('this is some content')

我想将临时文件夹变成真正的可下载 zip。

是的,有可能。
首先,您可以提供一个 API 来下载您的文件(Flask 示例)

from flask import Flask
from flask import Response
from flask import make_response
from flask import send_file
...
response = make_response(send_file(path_or_file=package_name, as_attachment=True, download_name='package.zip'))

其次,你必须形成你的文件。我曾经将文件作为 zip 存档发送,以保留文件和文件夹的结构:

import shutil
zip_file = shutil.make_archive(path_src, 'zip', path_dst)