i have some pictures in project root folder and i want to make them available to download dynamically as zip archive.
All the pictures have same name but the difference is in sequence number at the end, So i tried to do this
def zip_files(name, iterat):
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
for index in range(iterat):
filename = name+"_"+str(index)+".jpg"
archive.write(filename)
archive.close()
wrapper = FileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=test.zip'
response['Content-Length'] = temp.tell()
temp.seek(0)
return response
so i got errors in lines response['Content-Length'] = temp.tell()
and temp.seek(0)
Operation in closed file.
and when i comment those lines, the returned data to the ajax is empty (because this is triggered as an ajax request)
Update
I used the NamedTemporaryFile
as following :
def zip_files(name, iterat):
temp = tempfile.NamedTemporaryFile(delete=False)
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
for index in range(iterat):
filename = name+"_"+str(index)+".jpg"
archive.write(filename)
archive.close()
wrapper = FileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=test.zip'
archive = zipfile.ZipFile(temp.name, 'r')
response['Content-Length'] = open(temp.name).tell()
return response
now i have no errors in server side but the returned data to the ajax request still empty, in browser network tab all information added to HttpResponse
are in the Response Headers as following:
Content-Disposition: attachment; filename=test.zip
Content-Length: 0
Content-Type: application/zip
Date: Wed, 27 Mar 2019 15:32:08 GMT
Server: WSGIServer/0.2 CPython/3.7.2
X-Frame-Options: SAMEORIGIN