Flask (0.11.2) +python3.6
- Compatible with all major browsers, tested (Chrome,firefox,safari,ie,edge)
- Quote is to urlencode the file name and then adapt it to the Edge browser
from urllib.parse import quote # for python3# from urllib import quote for python2 @app.route(‘/file/download/<filename>‘, methods=[‘GET‘])def file_download(filename): filename=FILE_PATH+filename response = make_response(send_file(filename)) # basename = os.path.basename(filename) utf_filename=quote(basename.encode(‘utf-8‘) response.headers["Content-Disposition"] = "attachment;filename*=UTF-8‘‘{}".format(utf_filename) response.headers[‘Content-Type‘] = "application/octet-stream; charset=UTF-8" return response
"""Content-Disposition中的filename进行了两次URL转码。以汉字漫为例:第一次转码,漫变为%E6%BC%AB。第二次转码,%E6%BC%AB变为%25E6%25BC%25AB(第二次转码时,因为%是特殊字符,所以会转为%25)。前端下载时:Chrome浏览器可以自动执行两次URL解码,所以下载的文件名是正常的。IE浏览器只执行一次URL解码,所以下载的文件名是第一次编码的结果(%E6%BC%AB)(版本8,10验证问题存在)。火狐好像也不行。解决方案是在返回给前端前对Content-Disposition中的filename先进行一次URL解码(实际我是对filename这个参数进行了解码,因为文件服务器是用的第三方的。)。此外,当文件名为中文(未执行URL编码)字符串时,IE下载也为乱码,因为IE对中文字符串又执行了一次URL解码。解决方案是将中文字符串进行URL编码。所以,总结下来,关键的问题就在于IE浏览器对filename只进行一次解码,而chrome对这种情况是进行了优化的"""
Flask Download File Chinese name garbled Ultimate Solution Python3 version