Django HTTP Response没有正确命名文件

joh*_*4ta 2 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 
Run Code Online (Sandbox Code Playgroud)

图像添加到显示网页,显示何时添加temp.seek(0)以移动到开头. 在此输入图像描述

Pau*_* Bu 5

试试没有引号:

resp['Content-Disposition'] = 'attachment; filename=data.ZIP'
Run Code Online (Sandbox Code Playgroud)

我以前做过这个,总是没有引号.此外,文档指出:

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

你可以尝试改变mimetypecontent_type这样的:

resp = HttpResponse(wrapper, content_type="application/octet-stream")
Run Code Online (Sandbox Code Playgroud)

更新:这个答案文件在Python中总是空白,Django显示了一个有效的代码.您可以在某些视图中开箱即用.

希望这可以帮助!