Search code examples
pythondjangozipresponse

Send a zip file as a response using python


I am given a zip file that I need to send to UI from where it should be downloaded for the user. While testing on POSTMAN, using Send & Download button associated with POST, I am able to download the file. But when opening it, it says:

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

Here's the code I am trying:

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

The zip file read is valid as it's already on the local. Any ideas?


Solution

  • Rather than generate the response yourself, you can use a FileResponse which does it for you

    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'
            )