Reputation: 1547
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?
Upvotes: 0
Views: 2323
Reputation: 87074
You are sending the contents of the compressed files, omitting the metadata contained in the zip archive.
There is no reason to open the file as a zip file as no changes are made to the contents, so just open the file in byes mode and send it. I haven't tested this, but try this:
with open('./studies.zip', 'rb') as f:
response = HttpResponse(f)
response['Content-Type'] = 'application/zip'
response['Content-Disposition'] = 'attachment;filename=studies.zip'
Upvotes: 2