繁体   English   中英

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

[英]Django - generate Zip file and serve (in memory)

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

问题是即使它返回 Zip 文件,它也已损坏。

注意:我不能使用文件的绝对路径,因为我使用远程存储。

应在 memory zip 中生成的 model 方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM