可以使用 Django 的 HttpResponseFileWrapper 将压缩文件(ZIP 文件)返回给前端下载。

以下是示例代码:

import os
import zipfile
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper

def download_zip(request):
    # 创建压缩文件
    zip_filename = 'example.zip'
    zip_file = zipfile.ZipFile(zip_filename, 'w')
    zip_file.write('file1.txt')
    zip_file.write('file2.txt')
    zip_file.close()

    # 打开压缩文件并返回给前端下载
    zip_file = open(zip_filename, 'rb')
    response = HttpResponse(FileWrapper(zip_file), content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(zip_filename)
    response['Content-Length'] = os.path.getsize(zip_filename)
    return response

在上面的示例中,首先创建一个名为 example.zip 的压缩文件,并将 file1.txtfile2.txt 添加到其中。然后,打开压缩文件,并使用 HttpResponseFileWrapper 将其返回给前端下载。最后,设置 Content-DispositionContent-Length 头来指定文件名和文件大小。

Django 压缩文件下载:使用 HttpResponse 和 FileWrapper 返回 Zip 文件

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

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