如何使用 zipfile 和 urllib2 导出多个图像

how can I export multiple images using zipfile and urllib2

我正在尝试将多个图像文件添加到我的 zip 文件中。 我四处搜索,知道如何添加一个。我尝试遍历多个图像然后写入其中,但没有成功。

我对 txt 格式做了同样的事情,我可以将一些文件压缩到 zip 中,但不知何故,当使用图像时却不行。

# 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

这会给我最后一张图片,在某种程度上我可以理解为什么。

不要在每次迭代中都创建一个新的 zip 文件。相反,将所有文件写入同一个存档(您在循环之前实例化):

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