| 1 | import io |
| 2 | import os |
| 3 | import zipfile |
| 4 | from flask import Flask, send_file |
| 5 | from werkzeug.utils import secure_filename |
| 6 | |
| 7 | app = Flask(__name__) |
| 8 | |
| 9 | @app.route('/download-zip') |
| 10 | def download_zip(): |
| 11 | # 1. Sample data (could come from a database or list) |
| 12 | files_to_zip = [ |
| 13 | {"filename": "note_1.txt", "content": "Hello, this is the first file content."}, |
| 14 | {"filename": "data/config.json", "content": '{"status": "ok"}'}, |
| 15 | {"filename": "system_info_log_very_long_name_to_test_the_hundred_character_limit_requirement.log", "content": "System log: all clear."} |
| 16 | ] |
| 17 | |
| 18 | # 2. Prepare in-memory buffer |
| 19 | memory_file = io.BytesIO() |
| 20 | |
| 21 | # 3. Create the ZIP file inside the buffer |
| 22 | with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf: |
| 23 | for f in files_to_zip: |
| 24 | # Clean filename and handle the 100-character limit inline |
| 25 | clean_name = secure_filename(f['filename']) |
| 26 | name, ext = os.path.splitext(clean_name) |
| 27 | # Slice name to fit (100 - extension length) to keep total length <= 100 |
| 28 | safe_filename = "{}{}".format(name[:100-len(ext)], ext) |
| 29 | |
| 30 | # Write string content into the ZIP |
| 31 | zf.writestr(safe_filename, f['content']) |
| 32 | |
| 33 | # 4. Reset buffer pointer to the beginning so it can be read from the start |
| 34 | memory_file.seek(0) |
| 35 | |
| 36 | # 5. Send file to client without saving to disk |
| 37 | # Using attachment_filename for Python 3.7 / older Flask compatibility |
| 38 | return send_file( |
| 39 | memory_file, |
| 40 | mimetype='application/zip', |
| 41 | as_attachment=True, |
| 42 | attachment_filename='archive_data.zip' |
| 43 | ) |
| 44 | |
| 45 | if __name__ == '__main__': |
| 46 | app.run(debug=True) |
To add a comment, please login or register first.
Register or Login