import io import os import zipfile from flask import Flask, send_file from werkzeug.utils import secure_filename app = Flask(__name__) @app.route('/download-zip') def download_zip(): # 1. Sample data (could come from a database or list) files_to_zip = [ {"filename": "note_1.txt", "content": "Hello, this is the first file content."}, {"filename": "data/config.json", "content": '{"status": "ok"}'}, {"filename": "system_info_log_very_long_name_to_test_the_hundred_character_limit_requirement.log", "content": "System log: all clear."} ] # 2. Prepare in-memory buffer memory_file = io.BytesIO() # 3. Create the ZIP file inside the buffer with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf: for f in files_to_zip: # Clean filename and handle the 100-character limit inline clean_name = secure_filename(f['filename']) name, ext = os.path.splitext(clean_name) # Slice name to fit (100 - extension length) to keep total length <= 100 safe_filename = "{}{}".format(name[:100-len(ext)], ext) # Write string content into the ZIP zf.writestr(safe_filename, f['content']) # 4. Reset buffer pointer to the beginning so it can be read from the start memory_file.seek(0) # 5. Send file to client without saving to disk # Using attachment_filename for Python 3.7 / older Flask compatibility return send_file( memory_file, mimetype='application/zip', as_attachment=True, attachment_filename='archive_data.zip' ) if __name__ == '__main__': app.run(debug=True)