使用 python 发送 zip 文件作为响应

Send a zip file as a response using python

我得到了一个 zip 文件,我需要将其发送到 UI,用户应该从那里下载它。 在 POSTMAN 上进行测试时,使用与 POST 关联的“发送和下载”按钮,我能够下载该文件。但是打开它时,它说:

Windows cannot open the folder. The Compressed(zipped) folder <zip path> is invalid

这是我正在尝试的代码:

from django.response import Response
from rest_framework.views import APIView

def get_response():
    with open(zip_file_path.zip, 'r', encoding='ISO-8859-1') as f:
        file_data = f.read()
        response = Response(file_data, content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename="ReportTest.zip"'
    return response

class GenerateZIP(APIView):
    def post(self, request):
        zip_file_response = get_response()
        return zip_file_response

读取的zip文件有效,因为它已经在本地。 有什么想法吗?

您可以使用 FileResponse 为您生成响应,而不是自己生成响应

from django.http import FileResponse
from rest_framework.views import APIView


class GenerateZIP(APIView):
    def post(self, request):
        return FileResponse(
            open('zip_file_path.zip', 'rb'),
            as_attachment=True,
            filename='ReportTest.zip'
        )