zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    js完成打印功能
    ajax的序列化表单提交
    SpringMVC学习记录
    拦截器学习记录
    SpringMVC的controller层的方法返回值
    Mybatis学习记录(3)
    Mybatis学习记录(2)
    Mybatis学习记录(1)
    02-操作系统必会问题
    01-“计算机网络”必会问题
  • 原文地址:https://www.cnblogs.com/fuyuteng/p/15038771.html
Copyright © 2011-2022 走看看