【问题标题】:Python convert zip file to bytes streamPython将zip文件转换为字节流
【发布时间】:2021-03-02 02:49:41
【问题描述】:

我有一个 zip 文件,当我在本地打开它时,它看起来很棒。我想将其转换为字节流buffer,然后使用django 将其作为HttpResponse(buffer) 返回。代码是,

studies_zip = zipfile.ZipFile('./studies.zip', 'r')
buffer = io.BytesIO()
bytes = [zipfile.Path(studies_zip, at=file.filename).read_bytes() 
             for file in studies_zip.infolist()]

buffer = io.BytesIO()
buffer_writer = io.BufferedWriter(buffer)
[buffer_writer.write(b) for b in bytes]
buffer.seek(0)

response = HttpResponse(buffer)
response['Content-Type'] = 'application/zip'
response['Content-Disposition'] = 'attachment;filename=studies.zip'

在前端/UI 我明白了,

看起来不错,即 34.9MB 的显示大小比实际的 36.6MB 小一点。此外,当我尝试当场或在本地保存文件后打开文件时,我得到

怎么了?

【问题讨论】:

  • 顺便说一句,请不要将列表理解用于副作用:[buffer_writer.write(b) for b in bytes]

标签: python io zip


【解决方案1】:

您正在发送压缩文件的内容,省略了 zip 存档中包含的元数据。

没有理由将文件作为 zip 文件打开,因为内容没有任何更改,因此只需以再见模式打开文件并发送即可。我还没有测试过,但试试这个:

with open('./studies.zip', 'rb') as f:
    response = HttpResponse(f)
    response['Content-Type'] = 'application/zip'
    response['Content-Disposition'] = 'attachment;filename=studies.zip'

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    相关资源
    最近更新 更多