接下來會記錄一些,練習過程中實做的內容
1.先設定好本地圖片的目錄位置和回傳的ZIP檔名
2.使用 zipfile.ZipFile,創建了一個 ZIP 文件,並打開它以寫入模式
(會寫進設定好的zip_file_path)
3.使用 os.path.join() 函式組合 static_path 和 image_filename
,以獲取圖片文件的完整路徑
4.使用 os.path.exists() 檢查圖片文件是否存在
若圖片文件存在,則用zipf.write將該文件添加到 ZIP 文件中
5.最後return send_file ( zip_file_path ) 回傳ZIP檔給使用者
(as_attachment=True 表示文件視為附件,而不是在瀏覽器中顯示它)
from flask import Blueprint, request, send_file
import os
import zipfile
images = Blueprint('images', __name__)
@images.route('/download', methods=['GET'])
def download():
    # 設定靜態路徑目錄與檔案名稱
    static_path = 'static'
    image_filename = 'compal.jpg'
    # 創建壓縮文件
    zip_file_path = 'image.zip'
    
    with zipfile.ZipFile(zip_file_path, 'w', zipfile.ZIP_STORED) as zipf:
        # 獲取圖片文件的完整路徑
        file_path = os.path.join(static_path, image_filename)
        if os.path.exists(file_path):
            # 使用 arcname 參數指定文件名,不包含文件夾路徑
            zipf.write(file_path, arcname=image_filename)
        else:
            return '圖片文件不存在'
    # 返回zip
    return send_file(zip_file_path, as_attachment=True)
那實做後因為這種方式會在本地端留下檔案
因此也嘗試了另一種不在本地端留存zip檔案的方式
1.zip_buffer = io.BytesIO() 使用 BytesIO 創建一個 ZIP 內存數據
2.使用 zipfile.ZipFile 創建了一個 ZIP 文件,
將其存儲在 zip_buffer 中,因此 ZIP 數據將以二進制形式保存在內存中
4.最後return加上donwload_name設定下載後名稱
from flask import Blueprint, request, send_file,render_template
import os,io,zipfile
images = Blueprint('images', __name__)
@images.route('/')
def images_page():
    return render_template('images.html')
@images.route('/dowload', methods=['GET'])
def dowload():
    # 設定靜態路徑目錄與檔案名稱
    static_path = 'static'
    image_filename = 'compal.jpg'
    # 創建壓縮文件
    zip_buffer = io.BytesIO()  # 使用 BytesIO 創建一個 ZIP 數據流
    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_STORED) as zipf:
        # 獲取圖片文件的完整路徑
        file_path = os.path.join(static_path, image_filename)
        if os.path.exists(file_path):
            # 使用 arcname 參數指定文件名,不包含文件夾路徑
            zipf.write(file_path, arcname=image_filename)
        else:
            return '圖片文件不存在'
    # 將 ZIP 數據流轉換為 Response 物件,直接返回 ZIP 數據
    zip_buffer.seek(0)  # 將游標定位到 ZIP 數據的開頭
    return send_file(zip_buffer, as_attachment=True, download_name='image.zip')