【问题标题】:Downloading a file as attachment from a Django template is not working in firefox从 Django 模板下载文件作为附件在 Firefox 中不起作用
【发布时间】:2017-11-17 14:57:08
【问题描述】:

我有一个 Django 视图 (download-attachment),它返回一个 django.http.response.HttpResponse 对象。

对象的字典表示是:

{
    'reason_phrase': u'OK', 
    '_handler_class': None, 
    '_headers': {'content-length': ('Content-Length', '21'), 
                 'content-type': ('Content-Type', 'text/plain'),
                 'content-disposition': ('Content-Disposition', 'attachment; 
    filename="upload_file.txt"')
                }, 
    '_charset': None, 
    '_closable_objects': [], 
    'cookies': <SimpleCookie: >, 
    'closed': False, 
    '_container': ['Upload to file\n']
}

在模板中,点击超链接即可呈现视图:

<a href="{% url "download-attachment" certificationID=certificationID fileID=attachment.id %}" download> {{attachment.name}}</a>

这里的certificateID和fileID是下载附件视图的url参数。

在 chrome 中,单击超链接时,文件将作为附件下载,文件名在响应的 Content-Disposition 标头中给出。

在 Firefox 中,文件下载失败。需要帮助在 Firefox 中进行文件下载。

【问题讨论】:

  • 它失败了如何?你在 Django 中做什么来提供这些内容?
  • @DanielRoseman 在 Django 中,我正在创建一个 django.http.response.HttpResponse 类的对象。并从视图中返回该对象。 response = HttpResponse(data, content_type="text/plain") response["Content-Description"] = "File Transfer" response["Content-Disposition"] = "attachment; filename=\"%s\"" % self.cweResponse.get("file_name") response['Content-Length'] = self.cweResponse.get("size") return response在Firefox中,下载列表显示文件名失败,无法打开。

标签: html django django-templates


【解决方案1】:

不是客户端或模板问题。 Firefox 需要在响应的标头中设置 Content-Encoding 实体来下载文件附件。即使没有编码,也需要设置标头。为 Django HttpResponse 对象添加了 Content-Encoding。

对象的新字典表示为:

{
    'reason_phrase': u'OK', 
    '_handler_class': None, 
    '_headers': {'content-length': ('Content-Length', '21'), 
                 'content-type': ('Content-Type', 'text/plain'),
                 'content-encoding': ('Content-Encoding', 'None'),
                 'content-disposition': ('Content-Disposition', 'attachment; 
    filename="upload_file.txt"')
                }, 
    '_charset': None, 
    '_closable_objects': [], 
    'cookies': <SimpleCookie: >, 
    'closed': False, 
    '_container': ['Upload to file\n']
}

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 2011-03-13
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    相关资源
    最近更新 更多