是否可以制作 zip 存档并提供下载,但仍无法将文件保存到硬盘驱动器?
最佳答案
要触发下载,您需要设置 Content-Disposition
header :
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
header :
response['Content-Length'] = myfile.tell()
关于python - 使用 Django 生成要下载的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/908258/