django StreamingHttpResponse下载文件 Content-Type 文件名中文乱码问题
from django.http import StreamingHttpResponsedef downloadFile(request):download_name ='测试.docx'the_file_name = str(download_name) # 显示在弹出对话框中的默认的下载文件名filename = os.getcwd()+r'\templ...
·
from django.http import StreamingHttpResponse
def downloadFile(request):
download_name ='测试.docx'
the_file_name = str(download_name) # 显示在弹出对话框中的默认的下载文件名
filename = os.getcwd()+r'\templates\Doc\explore.docx' # 要下载的文件路径
response = StreamingHttpResponse(readFile(filename))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = "attachment; filename={}".format(the_file_name)
return response
下载文件名设置为英文或数字时可以正确下载。当文件名中包含中文,例如以上代码中的'测试.docx'会出现乱码。
print(response['Content-Disposition'])
结果:
=?utf-8?b?YXR0YWNobWVudDtmaWxlbmFtZSo9VVRGLTjllYrllYrllYouZG9jeA==?=
解决方法
使用指定编码,并告诉浏览器编码类型。
将原来代码中的
response['Content-Disposition'] = "attachment; filename={}".format(the_file_name)
修改为
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(the_file_name))

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)