0

I'm trying to put a zip file into an io.BytesIO buffer and then offer that for download. Below is what I've got (part of a longer views.py, I'm just posting the relevant part).

But I'm getting the following error message:

AttributeError at 'bytes' object has no attribute 'read'

Can anyone tell me what I'm doing wrong?

from django.http import HttpResponse
from wsgiref.util import FileWrapper
from zipfile import *
import io

buffer = io.BytesIO()

zipf = ZipFile(buffer, "w")
zipf.write ("file.txt")
zipf.close()

response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=file.zip'

return response

Edit: It's telling me the error is coming from the line:

response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip')
MBT
  • 21,733
  • 19
  • 84
  • 102
Rob Kwasowski
  • 2,690
  • 3
  • 13
  • 32

3 Answers3

5

I know this thread is a bit old, but still.

The getvalue() method of the BytesIO object returns the content in bytes which can be passed in to the HttpResponse with content_type='application/zip'.

buffer = io.BytesIO()
zipf = ZipFile(buffer, "w")
zipf.write ("file.txt")
zipf.close()
response = HttpResponse(buffer.getvalue(), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=file.zip'
return response
G Haridev
  • 51
  • 1
  • 2
3

You need to read the file in byte mode ('b')

try Changing

buffer = io.BytesIO()
zipf = ZipFile(buffer, "w")
zipf.write ("file.txt")
zipf.close()

to

zipf = zipfile.ZipFile("hello.zip", "w")
zipf.write("file.txt")
zipf.close()
response = HttpResponse(io.open("hello.zip", mode="rb").read(), content_type='application/zip')
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • It's telling me "ZipFile requires mode 'r', 'w', 'x', or 'a'" – Rob Kwasowski Jan 28 '18 at 16:51
  • From the docs it looks like you cannot write a buffer to zipfile module object – Rakesh Jan 28 '18 at 16:59
  • The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as defined in PKZIP Application Note.This module does not currently handle multi-disk ZIP files. It can handle ZIP files that use the ZIP64 extensions (that is ZIP files that are more than 4 GiB in size). It supports decryption of encrypted files in ZIP archives, but it currently cannot create an encrypted file. – Rakesh Jan 28 '18 at 17:01
  • No, I'm trying to put a zip file in a buffer. – Rob Kwasowski Jan 28 '18 at 17:01
0

Instead of having the file in memory and then sending it as a zip, I just saved the file onto the server and then sent it by following this example.

Rob Kwasowski
  • 2,690
  • 3
  • 13
  • 32