您可以使用 HttpResponse 来返回 zip 文件,设置 Content-Type 为 'application/zip',Content-Disposition 为 'attachment',filename 为您想要的文件名。以下是示例代码:

import zipfile
import io
from django.http import HttpResponse

def download_zip(request):
    # 创建一个zip文件
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, 'w') as zip_file:
        # 将文件添加到zip文件中
        file_path = 'path/to/your/file'
        zip_file.write(file_path)

    # 返回HttpResponse对象,Content-Type设置为application/zip,Content-Disposition设置为attachment
    # filename设置为您想要的文件名
    response = HttpResponse(buffer.getvalue(), content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename='your_file_name.zip''
    return response
Django 返回 Zip 文件给前端下载

原文地址: https://www.cveoy.top/t/topic/opup 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录