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

Django - generate Zip file and serve (in memory)

我正在尝试提供包含 Django 个对象图像的 zip 文件。

问题是即使 returns 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()

ViewSet 动作

@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()