我现在有奇怪的行为。比如,我在 StringIO 中有zip存档二进制数据。如果我将 HttpResponse 的内容参数设置为 StringIO.getvalue(),我会在客户端获取截断文件。 StringIO.read()和 FileWrapper(StringIO)的结果相同。截断文件的大小每次都不一样...如果我从磁盘 FileWrapper(文件('/ home / user1 / tempfile.zip'))读取文件,我会得到正确的文件。但我需要动态生成zip文件!
Django 1.4,Nginx 1.1.19
答案 0 :(得分:3)
看看这个:
import zipfile
from cStringIO import StringIO
from contextlib import closing
from django.http import HttpResponse
def foo(request):
...
with closing(StringIO()) as ff:
zipped = zipfile.ZipFile(ff, 'a')
for i, wb in enumerate(workbooks):
with closing(StringIO()) as f:
wb.save(f)
zipped.writestr('%s.xls' % (i + 1), f.getvalue())
zipped.close()
foo = ff.getvalue()
filename = 'foo.zip'
response = HttpResponse(mimetype="application/zip")
response['Content-Disposition'] = "attachment;filename=%s" % filename
response.write(foo)
return response