小编典典

生成文件以使用Django下载

django

是否可以制作一个zip存档并提供下载,但仍不将文件保存到硬盘驱动器?


阅读 387

收藏
2020-03-26

共1个答案

小编典典

要触发下载,你需要设置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

import cStringIO as StringIO

myfile = StringIO.StringIO()
while not_finished:
    # generate chunk
    myfile.write(chunk)

你也可以选择设置Content-Length标头:

response['Content-Length'] = myfile.tell()
2020-03-26