Django 下载功能中文文件名问题

from django.utils.encoding import escape_uri_path
from django.shortcuts import HttpResponse

def file_download(request):
    file_name = "凸凸.jpg"
    res = requests.get("https://nihaoshijie-17600663122-1588242519000-1301483025.cos.ap-beijing.myqcloud.com/%E5%87%B8%E5%87%B8.jpg")

    # 文件分块处理
    data = res.iter_content()

    # 设置内容类型 content_type=application/octet-stream (二进制流数据) 提示下载框
    response = HttpResponse(data, content_type="application/octet-stream")

    # 设置响应头:escape_uri_path中文件文件名转义
    response[‘Content-Disposition‘] = f"attachment; filename={escape_uri_path(file_name)};"
    ‘‘‘
    Content-Disposition可以控制用户请求所得的内容存为一个文件的时候提供一个默认的文件名,文件直接在浏览器上显示或者在访问时弹出文件下载对话框。
    如attachment为以附件方式下载,会直接在浏览器中显示,如果需要提示用户保存,就要利用Content-Disposition进行一下处理,关键在于一定要加上attachment
    ‘‘‘
    return response

相关推荐