生成文件以使用 Django 下载 [英] Generating file to download with Django
本文介绍了生成文件以使用 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
标头:
Optionally you can set Content-Length
header as well:
response['Content-Length'] = myfile.tell()
这篇关于生成文件以使用 Django 下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文