flask设置content-disposition正确显示中文

Flask 中的 Content-Disposition 头部字段可以用于指定浏览器如何处理服务器返回的文件,包括文件下载时的文件名。

如果你需要在 Content-Disposition 中使用中文文件名,可以使用 Unicode 编码,并将编码后的字符串传递给 Response 对象的 headers 参数。

 headers = ("Content-Disposition", f"inline;filename={user_info['fn'].encode('utf-8').decode('latin-1')}")
 as_attachment = False            
 response = make_response(send_file(file_path, as_attachment=as_attachment))
 response.headers[headers[0]] = headers[1]
 return response

将文件名先用 utf-8 编码,然后再用 latin-1 解码,这样 Content-Disposition 中正确显示中文文件名。

添加新评论