Python 将 zip 文件转换为字节流
Python convert zip file to bytes stream
我有一个 zip 文件,当我在本地打开它时它看起来很棒。我想将其转换为字节流 buffer
,然后使用 django
将其 return 转换为 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'
在 front-end/UI 我明白了,
看起来不错,即 34.9MB
的显示大小比实际 36.6MB
小一点。此外,当我尝试当场打开文件或在本地保存文件后,我得到
怎么了?
您发送的是压缩文件的内容,省略了 zip 存档中包含的元数据。
没有理由将文件作为 zip 文件打开,因为没有对内容进行任何更改,所以只需以 byes 模式打开文件并发送即可。我还没有测试过这个,但试试这个:
with open('./studies.zip', 'rb') as f:
response = HttpResponse(f)
response['Content-Type'] = 'application/zip'
response['Content-Disposition'] = 'attachment;filename=studies.zip'
我有一个 zip 文件,当我在本地打开它时它看起来很棒。我想将其转换为字节流 buffer
,然后使用 django
将其 return 转换为 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'
在 front-end/UI 我明白了,
看起来不错,即 34.9MB
的显示大小比实际 36.6MB
小一点。此外,当我尝试当场打开文件或在本地保存文件后,我得到
怎么了?
您发送的是压缩文件的内容,省略了 zip 存档中包含的元数据。
没有理由将文件作为 zip 文件打开,因为没有对内容进行任何更改,所以只需以 byes 模式打开文件并发送即可。我还没有测试过这个,但试试这个:
with open('./studies.zip', 'rb') as f:
response = HttpResponse(f)
response['Content-Type'] = 'application/zip'
response['Content-Disposition'] = 'attachment;filename=studies.zip'