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