python - 使用 Django 生成要下载的文件

标签 python django

是否可以制作 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/

相关文章:

java - 在java和python之间传递数据

Python:使lib使用重新定义的类

python - Select_Related 和 JSON - 如何序列化外键对象

python - Django / Cassandra : can not createsuperuser

Django如何为电子邮件激活链接生成自动激活 key

Python 2.7.5 如何从用户输入中累积和声明数组/列表中的值?

python - 解密雅虎财经中的日期序列号

python - 逐行替换字符串

django - 如何在 django 中显示 shamsi 日期?

Django celery daemon 给出 'supervisor FATAL can' t find command',但路径是正确的