Compress and download a temporary folder with a browser

Viewed 39

Is there a way to compress a temporary folder (like folder1) containing files and folders into a zip file and launch the download of this zip file in a browser?

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')

I would like to turn the temporary folder into a real downloadable zip.

1 Answers

Yes, it it possible.
First, you can provide an API to download your file (Flask example)

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'))

Second, you have to form your file. I've used to send files as a zip archive that keeps the structure of the files and folders:

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