根据 python / tornado 中的 rfc 5987 对文件名进行编码

Encode filename according to rfc 5987 in python / tornado

从 I learnt that the encoding defined in RFC 5987 is used to encode filenames in Content-disposition headers. And from 我了解到至少从 2012 年 11 月开始,主流浏览器的支持就很好。这两个问题都很老了,但我找不到根据[中的这种编码对文件名进行编码的标准方法] =19=]/龙卷风。我有一个

self.set_header('Content-Disposition', 'attachment;filename="{}.{}"'.format(basename, format))

在我的代码中,当 basename 包含 latin1 之外的字符时失败,我正在寻找一种标准的编码方式。

您可以使用urllib.parse.quote进行编码。只需添加 filename*=UTF-8'' 的样板。例如,这个简单的服务器提供一个 UTF-8 文件名的文件:

import tornado.httpserver
import tornado.ioloop
import tornado.web

import urllib.parse

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        filename = 'file "\'ä↭.txt'
        encoded_filename = urllib.parse.quote(filename, encoding='utf-8')
        self.set_header(
            'Content-Disposition',
            'attachment;filename*=UTF-8\'\'{}'.format(encoded_filename))
        self.write('text file with file name file "\'ä↭.txt.\n')
        self.write('Most browsers will encode the " as _ or so.')


application = tornado.web.Application([
    (r"/", MainHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.current().start()