Skip to content
Build From Zero

How to generate a zip file from given file list?

Tutorial, Python, Django1 min read

app/mixins.py
1import os
2import shutil
3from io import BytesIO
4from zipfile import ZipFile
5from django.core.files.storage import FileSystemStorage
6from django.http import HttpResponse
7from django.conf import settings
8
9local_storage = FileSystemStorage()
10
11
12class ZipResponseMixin:
13 def response(self, request, files: list, folder_name: str) -> HttpResponse:
14 """Zip Response
15 Generate a zip file from given file list and return Http response (Force download)
16 :param request: request Object
17 :param files: list of file like objects saved in models
18 :param folder_name: desired folder name
19 :return:
20 """
21 folder_abs_path = f"{settings.MEDIA_ROOT}/temp-dl/{str(request.user.first_name)}/{folder_name}"
22 if os.path.exists(folder_abs_path):
23 shutil.rmtree(folder_abs_path)
24 os.makedirs(folder_abs_path)
25 file_names = list()
26 for file in files:
27 self._temp_save(file, file_names, folder_abs_path)
28 buffer = BytesIO()
29 zf = ZipFile(buffer, "w")
30 for name in file_names:
31 file_abs_path = folder_abs_path + "/" + name
32 zf.write(file_abs_path, name)
33 zf.close()
34 response = HttpResponse(buffer.getvalue(), content_type="application/zip")
35 response["Content-Disposition"] = f"attachment; filename={folder_name}.zip"
36 return response
37
38 def _temp_save(self, file, file_names, folder_abs_path):
39 if file is not None:
40 file_name = os.path.basename(file.name)
41 file_abs_path = folder_abs_path + "/" + file_name
42 local_storage.save(file_abs_path, file)
43 file_names.append(file_name)
© 2021 by Build From Zero. All rights reserved.
Theme by LekoArts