【问题标题】:Django HTTP Response not naming file correctlyDjango HTTP 响应未正确命名文件
【发布时间】:2013-06-25 13:12:37
【问题描述】:

我有一个 Django 脚本,它可以压缩服务器上的文件,并在向服务器发送查询时将压缩文件发送出去。但是,zip 文件以“下载”而不是 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) 移动到开头。

【问题讨论】:

    标签: python django


    【解决方案1】:

    不带引号试试:

    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 显示了一个有效的代码。您可以在某些视图中开箱即用地对其进行测试。

    希望这会有所帮助!

    【讨论】:

    • 我刚试了一下,还是不行。我在它周围加了双引号,因为我在网上看到一些地方,如果文件名周围没有双引号,一些浏览器将无法识别它。但是无论有没有引号,它都不起作用。不过谢谢!
    • 实际上,在文档中,有引号。你读过content_type吗?我认为这可能是另一个问题。我能够用一些最少的代码让它工作一次,我会把它分享给你,看看它是否在你的盒子里工作。更新了我的答案
    • 我尝试了所有不同的内容类型,例如 application/zip、application/octet-stream 和 application/x-zip-compressed,但没有一个产生任何不同的结果。
    • 您的答案中的代码有效,但是,根据该答案,我无法让我的代码工作。我尝试将 temp.seek(0) 移到开头,浏览器显示只是打开了一个网页并且不下载任何内容。如果有帮助,我会在我的主要答案中添加一个屏幕截图。
    • 既然 tell 只是说出文件中的当前位置,也许你可以尝试不使用Content-Length,这似乎不是问题,而只是一个想法。另外,以防万一,请从其他浏览器尝试。这应该是一个简单的修复:(不明白为什么给我们带来这么多麻烦:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多