У меня есть несколько изображений в корневой папке проекта, и я хочу сделать их доступными для динамической загрузки в виде zip-архива.
Все изображения имеют одинаковое имя, но разница в порядковом номере в конце, поэтому япопытался сделать это
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
, поэтому я получил ошибки в строках response['Content-Length'] = temp.tell()
и temp.seek(0)
Операция в закрытом файле.
икогда я комментирую эти строки, возвращаемые данные в ajax пустые (потому что это запускается как запрос ajax)
Update
Я использовал NamedTemporaryFile
какследующее:
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
теперь у меня нет ошибок на стороне сервера, но возвращенные данные в запрос ajax все еще пустые, на вкладке сети браузера вся информация, добавленная к HttpResponse
, находится в заголовках ответа следующим образом:
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