发送带有UTF-8字符的附件时,Flask会引发UnicodeEncodeError(latin-1)

时间:2017-11-30 14:20:53

标签: python flask utf-8

我正在按烧瓶创建文件服务器。当我测试下载功能时,如果我尝试下载以UTF-8字符命名的文件,我发现它会引发UnicodeEncodeError。

upload/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)

你会得到一个例外,应该是这样的:

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)

1 个答案:

答案 0 :(得分:1)

问题是当使用as_attachement=True时,文件名会在标题中发送。不幸的是,烧瓶似乎还不支持rfc5987,它指定了如何使用除latin1之外的其他编码对附件文件名进行编码。

在这种情况下,最简单的解决方案是删除as_attachement=True,然后不会使用Content-Disposition标头发送,这可以避免此问题。

如果您真的必须发送Content-Disposition标题,可以尝试the related issue中发布的代码:

    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

这应该是fixed in the next release(&gt; 0.12)