Django - 生成并提供(在内存中)Zip文件

3

我正在尝试提供包含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文件时,它显示为损坏。

您知道如何使其正常工作吗?

1个回答

4
你犯了一个新手错误,没有在打开文件(这里是 ZipFile)后调用 close / 关闭文件。最好将 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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接