Django-下载文件设置响应头和兼容中文

前端点击下载按钮,发送请求到后端流程是这样:

 前端HTML:

<a class="btn btn-default btn-xs" href="{% url 'web:file_download' project_id=request.tracer.project.id file_id=item.id %}">
    <i class="fa fa-cloud-download" aria-hidden="true"></i>
</a>

URL:

url(r'^file/download/(?P<file_id>d+)$', file.file_download, name='file_download'),

视图函数:views->file.py

def file_download(request,project_id,file_id):
    """下载文件"""
    #文件内容;去cos获取文件内容
    # with open('xxx.png',mode="rb") as f:
    #     data = f.read()
    file_object = models.FileRepository.objects.filter(project_id=project_id,id=file_id).first()
    filepath = file_object.file_path
    #像地址发送请求
    res = requests.get(filepath)
    # 获取文件内容
    # data = res.content
    #文件分块处理(适用于大文件)
    data = res.iter_content()
    """方法一"""
    # response = HttpResponse(data)#response对象
    # #设置响应头
    # response['Content-Disposition'] = "attachment; filename={}".format(file_object.name)
    # return response

    """方法二"""
    #设置content_type=application/octet-stream 用于提示下载框
    response = HttpResponse(data, content_type="application/octet-stream")
    from django.utils.encoding import escape_uri_path
    #设置响应头:中文文件名转义
    response['Content-Disposition'] = "attachment; filename={};".format(escape_uri_path(file_object.name))
    return response
原文地址:https://www.cnblogs.com/fuyuteng/p/15038771.html