【问题标题】:Turbogears response - sending a utf-8 filenameTurbogears 响应 - 发送 utf-8 文件名
【发布时间】:2014-11-23 15:39:32
【问题描述】:

我正在使用 Turbogears 2.3.3 开发一个 web 应用程序
在我的应用程序中,用户将获得一组路线,他们需要相应地下载一些文件。
重要的是,他们将能够下载具有原始名称的文件,该名称将采用 utf8 格式。 这是我下载文件的方法:

import os
from webob.static import FileApp
from tg import expose, request, use_wsgi_app, response

....

@expose()
def download(self,**kw):
    response.headerlist.append(('Content-Disposition','attachment'))
    path_to_file = os.path.join(os.path.dirname(dfuswebapp.__file__), 'PrintFiles')
    file_with_path = os.path.join(path_to_file,kw['filename'])
    file = FileApp(file_with_path)
    return use_wsgi_app(file)

当我尝试获取这样的文件时,文件名是“下载”,带有原始文件的扩展名。

如果我尝试这段代码:

response.headerlist.append(('Content-Disposition','attachment;filename=%s'%str(kw['filename']))) 

如果 kw['filename'] 是 utf-8 格式,我会收到一个错误,我的大部分文件都是这样。 有没有办法获得原始文件名?

感谢您的帮助

【问题讨论】:

    标签: python-2.7 utf-8 response turbogears2


    【解决方案1】:

    遗憾的是,您遇到了 WSGI 和 HTTP 中的许多黑暗角落之一。 正如 WSGI 规范所述:

    还要注意,传递给 start_response() 的字符串是作为状态或作为 响应标头在编码方面必须遵循 RFC 2616。那 也就是说,它们必须是 ISO-8859-1 字符,或者使用 RFC 2047 MIME 编码。

    这意味着您的标头应编码为latin-1 或使用RFC2047,问题是由于浏览器的行为不可靠,到目前为止,webob 已排除对 latin-1 之外的标头的支持(见https://github.com/Pylons/webob/issues/11#issuecomment-2819811)。

    最好的解决方案可能是使用RFC6266 手动编码Content-Disposition 标头,它为使用percentage encoding 的unicode 编码提供filename*。这将提供一个完全符合 latin-1 的结果,让 WSGI 满意,并且可以表示 unicode UTF8 字符。

    这是一个简短的示例,根据浏览器给出“欧元汇率”和“欧元汇率”:

    Content-Disposition: attachment;
                              filename="EURO rates";
                              filename*=utf-8''%e2%82%ac%20rates
    

    有关此问题的讨论,另请参阅 StackOverflow 上的这篇文章: How to encode the filename parameter of Content-Disposition header in HTTP?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 2023-03-12
      相关资源
      最近更新 更多