如何为 HTTP 标头编码 UTF8 文件名?(Python,Django)

2022-01-17 00:00:00 python django http-headers http escaping

问题描述

我对 HTTP 标头有疑问,它们是用 ASCII 编码的,我想提供一个视图来下载名称可以是非 ASCII 的文件.

response['Content-Disposition'] = '附件;文件名="%s"' % (vo.filename.encode("ASCII","re​​place"), )

我不想使用静态文件来解决非 ASCII 文件名的相同问题,但在这种情况下,文件系统和文件名编码会出现问题.(我不知道目标操作系统.)

我已经尝试过 urllib.quote(),但是它引发了 KeyError 异常.

可能我做错了什么,但也许这是不可能的.

解决方案

这是一个常见问题.

没有可互操作的方法来做到这一点.一些浏览器实现专有扩展(IE、Chrome),另一些实现 RFC 2231(Firefox、Opera).

请参阅 http://greenbytes.de/tech/tc2231/ 上的测试用例..p>

更新:截至 2012 年 11 月,所有当前桌面浏览器都支持 RFC 6266 和 RFC 5987 中定义的编码(Safari >= 6、IE >= 9、Chrome、Firefox、Opera、Konqueror).

I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII.

response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), )

I don't want to use static files serving for same issue with non ASCII file names but in this case there would be a problem with File system and it's file name encoding. (I don't know target os.)

I've already tried urllib.quote(), but it raises KeyError exception.

Possibly I'm doing something wrong but maybe it's impossible.

解决方案

This is a FAQ.

There is no interoperable way to do this. Some browsers implement proprietary extensions (IE, Chrome), other implement RFC 2231 (Firefox, Opera).

See test cases at http://greenbytes.de/tech/tc2231/.

Update: as of November 2012, all current desktop browsers support the encoding defined in RFC 6266 and RFC 5987 (Safari >= 6, IE >= 9, Chrome, Firefox, Opera, Konqueror).

相关文章