本文介绍了使用Django生成文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以制作zip存档并提供下载,但仍然不能将文件保存到硬盘驱动器?
Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?
推荐答案
要触发下载,您需要设置 Content-Disposition
标题:
To trigger a download you need to set 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
If you don't want the file on disk you need to use StringIO
import cStringIO as StringIO
myfile = StringIO.StringIO()
while not_finished:
# generate chunk
myfile.write(chunk)
您还可以设置 Content-Length
标题:
response['Content-Length'] = myfile.tell()
这篇关于使用Django生成文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!