原因是不同浏览器对于下载文件文件名的编码解析格式不一样,常用浏览器解析格式如下:
- IE浏览器,采用URLEncoder编码
- Opera浏览器,采用filename*方式
- Safari浏览器,采用ISO编码的中文输出
- Chrome浏览器,采用Base64编码或ISO编码的中文输出
- FireFox浏览器,采用Base64或filename*或ISO编码的中文输出
如果硬来的话就是在后台把文件名先 encode 成 bytes,再判断浏览器,根据不同的浏览器用相应的编码decode一下就好了。
代码如下:
def download_file(request):
if request.method=="GET":
return render(request,"COVID_19Analyse/filedown.html")
country = request.POST.get("country")
print(country)
path = os.path.abspath(os.path.dirname(__file__))
the_file_name = '国际情况.xlsx'
filename = path+'/static/COVID_19Analyse/Upload/'+the_file_name
file = open(filename,"rb")
response = FileResponse(file)
response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
response['Content-Disposition'] = 'attachment; ' \
'filename=' + the_file_name.encode('utf-8').decode('ISO-8859-1')
return response
重点是这句话:要设置好编码。
response['Content-Disposition'] = 'attachment; ' \
'filename=' + the_file_name.encode('utf-8').decode('ISO-8859-1')