是否可以制作一个zip存档并提供下载,但仍不将文件保存到硬盘驱动器?
要触发下载,你需要设置Content-Disposition标题:
Content-Disposition
from django.http import HttpResponse from wsgiref.util import FileWrapper # generate the file response = HttpResponse(FileWrapper(myfile.getvalue()), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.zip' return response
如果你不想将文件放在磁盘上,则需要使用 StringIO
StringIO
import cStringIO as StringIO myfile = StringIO.StringIO() while not_finished: # generate chunk myfile.write(chunk)
你也可以选择设置Content-Length标头:
Content-Length
response['Content-Length'] = myfile.tell()