Django 文件下载一直未默认名称,设置header不管用(中文名无法使用,英文名正常)

原因是不同浏览器对于下载文件文件名的编码解析格式不一样,常用浏览器解析格式如下:

  • 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')

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值