python - 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,
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
What's wrong?
解决方案
您正在发送压缩文件的内容,省略了 zip 存档中包含的元数据。
没有理由将文件作为 zip 文件打开,因为内容没有任何更改,因此只需以再见模式打开文件并发送即可。我没有测试过这个,但试试这个:
with open('./studies.zip', 'rb') as f:
response = HttpResponse(f)
response['Content-Type'] = 'application/zip'
response['Content-Disposition'] = 'attachment;filename=studies.zip'
推荐阅读
- vue.js - 在 vuetify 中左右移除 padding/magrin
- python - 我正在尝试为我的代码的一部分导入图像,但它没有显示,但是它在不同的部分中进一步显示
- loops - 完成 2 个 goroutine 后删除文件
- r - 将用户定义的函数应用于小标题
- docusignapi - 在文档/模板上设置数据字段,供所有用户查看为只读
- css - 角材料容器没有扩展到填充页面?
- xamarin - Xamarin tesseract OCR 返回错误的输出和乱码
- laravel - Laravel route() 参数 UTF-8 问题
- html - 如何在 Flex 设计中使水平居中的导航链接更紧密?
- api - 如何使用 MarkLogic 搜索 API 获得一些特定的结果