Python 使用UTF-8字符发送附件时,Flask会引发UnicodeError(拉丁文-1)

Python 使用UTF-8字符发送附件时,Flask会引发UnicodeError(拉丁文-1),python,flask,utf-8,Python,Flask,Utf 8,我正在通过flask创建一个文件服务器。当我测试下载功能时,我发现如果我尝试下载以UTF-8字符命名的文件,会引发UnicodeDeer错误 在上载/1512026299/%E6%97%A0%E6%A0%87%E9%A2%98.png创建一个文件,然后运行以下代码: @app.route('/getfile/<timestamp>/<filename>') def download(timestamp, filename): dirpath = os.path.j

我正在通过flask创建一个文件服务器。当我测试下载功能时,我发现如果我尝试下载以UTF-8字符命名的文件,会引发UnicodeDeer错误

在上载/1512026299/%E6%97%A0%E6%A0%87%E9%A2%98.png创建一个文件,然后运行以下代码:

@app.route('/getfile/<timestamp>/<filename>')
def download(timestamp, filename):
    dirpath = os.path.join(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'upload'), timestamp)
    return send_from_directory(dirpath, filename, as_attachment=True)

问题是当使用
as_attachement=True
时,文件名会在标题中发送。不幸的是,flask似乎还不支持指定如何用latin1以外的其他编码编码附件文件名

在这种情况下,最简单的解决方案是删除
作为_attachement=True
,这样它就不会与
内容处置
标题一起发送,从而避免了这个问题

如果您确实需要发送
内容处置
标题,您可以尝试在以下位置发布代码:

这应该是(>0.12)

127.0.0.1 - - [30/Nov/2017 21:39:05] "GET /getfile/1512026299/%E6%97%A0%E6%A0%87%E9%A2%98.png HTTP/1.1" 200 -
Error on request:
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\werkzeug\serving.py", line 209, in run_wsgi
    execute(self.server.app)
  File "C:\Program Files\Python36\lib\site-packages\werkzeug\serving.py", line 200, in execute
    write(data)
  File "C:\Program Files\Python36\lib\site-packages\werkzeug\serving.py", line 168, in write
    self.send_header(key, value)
  File "C:\Program Files\Python36\lib\http\server.py", line 508, in send_header
    ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict'))
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 43-45: ordinal not in range(256)
    response = make_response(send_file(out_file))
    basename = os.path.basename(out_file)
    response.headers["Content-Disposition"] = \
        "attachment;" \
        "filename*=UTF-8''{utf_filename}".format(
            utf_filename=quote(basename.encode('utf-8'))
        )
    return response