0

I want to download multiple files in Django without creating zip acrhive. I have a valid which uses zip (create 1 zip file and download it)

But I have to implement downloading several files without zip archive creating. How can I modify my code?

class DocumentView(GenericAPIView):

    def get(self, request, *args, **kwargs):    
        document_type = kwargs.get("document_type", None)
        user_id = kwargs.get("user_id", None)

        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            raise NotFound("This is user not found.")

        if document_type == 'vehicle_photo':
            user_vehicle = user.vehicle.select_related().first()
            documents = user_vehicle.photos.all()
        else:
            documents = user.document_owner.select_related().filter(document_type=document_type)

        in_memory = BytesIO()
        zip_filename = f"{document_type}_{user_id}.zip"
        zip_archive = ZipFile(in_memory, "w")

        for document in documents:
            f_dir, f_name = os.path.split(document.photo.url if document_type == "vehicle_photo" else
                                          document.file.url)
            zip_path = f"{settings.ROOT_DIR}{f_dir}"
            zip_archive.write(zip_path+"/"+f_name, f_name)

        # Save zip file
        zip_archive.close()

        response = HttpResponse(content_type="application/zip")
        response['Content-Disposition'] = f'attachment; filename={zip_filename}'
        in_memory.seek(0)
        response.write(in_memory.read())

        return response
swor
  • 751
  • 3
  • 8
  • 21
  • 2
    I'm not sure that you can send multiple files in a single response. What's wrong with using zip? – markwalker_ Apr 05 '21 at 20:47
  • 3
    To the best of my knowledge this is not possible from the server side. You can simulate opening multiple links from the client side using javascript to emulate this but would require creating separate endpoints for each file: https://stackoverflow.com/questions/18451856/how-can-i-let-a-user-download-multiple-files-when-a-button-is-clicked – azundo Apr 05 '21 at 20:48
  • 2
    Right. One click == one result. That's the rule. You could put multiple links on your page and allow the user to right-click and download one at a time, but you can't force multiple files in a single request. – Tim Roberts Apr 05 '21 at 20:54

0 Answers0