django FileResponse 解决中文命名文件下载后乱码问题

时间:2022-07-22
本文章向大家介绍django FileResponse 解决中文命名文件下载后乱码问题,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
from django.utils.encoding import escape_uri_path  # 用于解决中文命名文件乱码问题
def excel(request):
    # df=pd.read_excel('测试.xlsx')
    # ht=df.to_html()
    # with open('./测试.xlsx', 'rb')as f:
        # df = f.read()
    df=open('./测试.xlsx) # 这里需要用open打开,如果用with open 打开的话会造成读取失败,
    name = "测试.xlsx"
    response = FileResponse(df)
    response['Content-Type'] = 'application/octet-stream' # 让浏览器知道这是一个下载文件
    # 解决文件下载中文命名出现乱码的情况
    response["Content-Disposition"] = "attachment; filename={0}".format(escape_uri_path(name))
    return response

在url中加入一条路由即可直接使用,亲测有效