Django HTTP Response没有正确命名文件

时间:2013-06-25 13:12:38

标签: python django

我有一个Django脚本,可以在服务器上压缩文件,并在将查询发送到服务器时将zip文件发送出去。但是,zip文件不断下载名称为“download”而不是data.ZIP,data.ZIP是指定名称的名称。有什么想法吗?我的代码如下。提前致谢!我省略了导入一些图像和html的部分代码,因为我不相信它们是问题的一部分,但我可以在必要时提供。

from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
import os
import sys
import zipfile
import tempfile
import StringIO

def index(req):

    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    # Open StringIO to grab in-memory ZIP contents
    s = StringIO.StringIO()
    fileList = os.listdir('/tmp/images')
    fileList = ['/tmp/images/'+filename for filename in fileList]
    # The zip compressor
    zip = zipfile.ZipFile(s, "w")
    for file in fileList:
        archive.write(file, os.path.basename(file)) 
    zip.close()
    archive.close()
    wrapper = FileWrapper(temp)
    #Get zip file, set as attachment, get file size, set mime type
    resp = HttpResponse(wrapper, mimetype = "application/octet-stream")
    resp['Content-Disposition'] = 'attachment; filename="data.ZIP"'
    resp['Content-Length'] = temp.tell()
    temp.seek(0)
    return resp 

图片已添加到显示网页,该网页显示添加temp.seek(0)以移至开头的时间。 enter image description here

1 个答案:

答案 0 :(得分:5)

尝试不加引号:

resp['Content-Disposition'] = 'attachment; filename=data.ZIP'

我以前做过这个,总是没有引号。此外,the docs指出:

  

要告诉浏览器将响应视为文件附件,请使用content_type参数并设置Content-Disposition标头。

您可以尝试使用mimetype更改content_type,如下所示:

resp = HttpResponse(wrapper, content_type="application/octet-stream")

更新:此答案File downloaded always blank in Python, Django显示了有效的代码。您可以在某些视图中开箱即用。

希望这有帮助!