2017-02-04 1 views
0

내 이미지 파일을 여러 개 추가하려고합니다. 나는 하나를 추가하는 방법을 알고 탐색했다. 여러 이미지를 반복하여 그 이미지를 쓰려고했지만 작동하지 않았습니다.zipfile 및 urllib2를 사용하여 여러 이미지를 내보내려면 어떻게해야합니까? - django

나는 txt 형식으로 똑같은 일을했으며 파일로 압축 할 수있는 몇 가지 파일이 있지만 어떻게 든 이미지가없는 경우에는 작동하지 않습니다.

나를 도와 줄 수 있습니까? 미리 감사드립니다.

# 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 

이렇게하면 왜 마지막으로 이미지가 표시되는지 알 수 있습니다.

답변

2

반복 할 때마다 새 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() 
+0

세상에 대신, (당신이 전에 루프를 의 인스턴스) 같은 아카이브에있는 모든 파일을 쓰기! 나는'f = StringIO()'을 루프 밖으로 옮겨서 작동하지 않았지만, 나는'zip = ZipFile (f, 'w')'를 생각하지 않았다. – Dora

관련 문제