如何使用 zipfile 和 urllib2 导出多个图像 - django [英] how can I export multiple images using zipfile and urllib2 - django
问题描述
我正在尝试将多个图像文件添加到我的 zip 文件中.我四处搜索,知道如何添加一个.我尝试遍历多个图像然后写入其中,但没有成功.
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.
我对 txt 格式做了同样的事情,它的工作原理是我可以将一些文件压缩到 zip 中,但在使用图像时却不能.
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.
有人可以帮我一把吗?提前致谢.
Can someone please give me a hand? Thanks in advance.
# 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.
推荐答案
不要在每次迭代中都创建一个新的 zip 文件.相反,将所有文件写入同一个存档(您在循环之前实例化):
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()
这篇关于如何使用 zipfile 和 urllib2 导出多个图像 - django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!