1

我现在有奇怪的行为。比如说,我在StringIO中有 zip 存档二进制数据。如果我将HttpResponse的内容参数设置为StringIO.getvalue(),我会在客户端得到截断的文件。StringIO.read()FileWrapper(StringIO)的结果相同。截断文件的大小每次都不同......如果我从磁盘FileWrapper(file('/home/user1/tempfile.zip'))读取文件,我会得到正确的文件。但我需要即时生成 zip 文件!

Django 1.4,Nginx 1.1.19

4

1 回答 1

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
于 2012-09-19T18:50:48.913 回答