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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章