首页 > 解决方案 > Python convert zip file to bytes stream

问题描述

I have a zip file that when I open it locally it looks great. I want to convert it to a bytes stream buffer and then return it as HttpResponse(buffer) using django. The code is,

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'

At the front-end/UI I get this,

enter image description here

that looks fine i.e. the displayed size of 34.9MB is a little bit less than the actual 36.6MB. Also, when I try to open the file either on the spot or after saving it locally, I get

enter image description here

What's wrong?

标签: pythoniozipfile

解决方案


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

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

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

推荐阅读