PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label python-zipfile. Show all posts
Showing posts with label python-zipfile. Show all posts

Thursday, May 5, 2022

[FIXED] how can I export multiple images using zipfile and urllib2

 May 05, 2022     django, image, python, python-zipfile, zip     No comments   

Issue

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

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()


Answered By - user2390182
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing