Python Django-生成Zip文件并提供服务(内存中)
我正在尝试提供一个包含Python Django-生成Zip文件并提供服务(内存中),python,django,zip,Python,Django,Zip,我正在尝试提供一个包含Django对象图像的zip文件 问题是,即使它返回Zip文件,它也已损坏 注意:我不能使用文件的绝对路径,因为我使用远程存储 应在内存中生成zip的模型方法 def generate_images_zip(self) -> bytes: content = BytesIO() zipObj = ZipFile(content, 'w') for image_fieldname in self.images_fieldnames():
Django
对象图像的zip
文件
问题是,即使它返回Zip文件,它也已损坏
注意:我不能使用文件的绝对路径,因为我使用远程存储
应在内存中生成zip的模型方法
def generate_images_zip(self) -> bytes:
content = BytesIO()
zipObj = ZipFile(content, 'w')
for image_fieldname in self.images_fieldnames():
image = getattr(self, image_fieldname)
if image:
zipObj.writestr(image.name, image.read())
return content.getvalue()
视图集操作
@action(methods=['get'], detail=True, url_path='download-images')
def download_images(self, request, pk=None) -> HttpResponse:
product = self.get_object()
zipfile = product.generate_images_zip()
response = HttpResponse(zipfile, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=images.zip'
return response
当我试图打开下载的Zip文件时,它说它已损坏
你知道如何让它工作吗?你犯了一个新手错误,没有调用
close
/关闭文件(ZipFile
),打开文件后,最好使用ZipFile
作为上下文管理器:
def generate_images_zip(self) -> bytes:
content = BytesIO()
with ZipFile(content, 'w') as zipObj:
for image_fieldname in self.images_fieldnames():
image = getattr(self, image_fieldname)
if image:
zipObj.writestr(image.name, image.read())
return content.getvalue()
天哪,谢谢!我没注意到。