'how can I export multiple images using zipfile and urllib2

I am trying to add multiple image files into my zip. I have searched around and knows how to add a single one. I tried to loop through multiple images then write into it but it didn't work.

I kind of did the same thing with txt format and it works that I can compress a few files into the zip but somehow not when with image.

# get all photos in db which will be a queryset as result
photos = Photo.objects.all()

# loop through the queryset
for photo in photos:
    # open the image url
    url = urllib2.urlopen(photo.image.url)
    # get the image filename including extension
    filename = str(photo.image).split('/')[-1]
    f = StringIO()
    zip = ZipFile(f, 'w')
    zip.write(filename, url.read())
zip.close()
response = HttpResponse(f.getvalue(), content_type="application/zip")
response['Content-Disposition'] = 'attachment; filename=image-test.zip'
return response

This would give me the last image which in a way I can see why.



Solution 1:[1]

Don't create a new zip file in every iteration. Instead, write all the files to the same archive (which you instantiate before the loop):

f = StringIO()
zip = ZipFile(f, 'w')

for photo in photos:
    url = urllib2.urlopen(photo.image.url)
    filename = str(photo.image).split('/')[-1]
    zip.write(filename, url.read())
zip.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2390182