zoukankan      html  css  js  c++  java
  • django三种文件下载方式

    一、概述

    在实际的项目中很多时候需要用到下载功能,如导excel、pdf或者文件下载,当然你可以使用web服务自己搭建可以用于下载的资源服务器,如nginx,这里我们主要介绍django中的文件下载。

    实现方式:a标签+响应头信息(当然你可以选择form实现)

    <div class="col-md-4"><a href="{% url 'download' %}">点我下载</a></div>
    方式一:使用HttpResponse

    路由url:

     url(r'^download/',views.download,name="download"),

    views.py代码

    from django.shortcuts import HttpResponse
    def download(request):
        file = open('crm/models.py', 'rb')
        response = HttpResponse(file)
        response['Content-Type'] = 'application/octet-stream' #设置头信息,告诉浏览器这是个文件
        response['Content-Disposition'] = 'attachment;filename="models.py"'
        return response
    方式二:使用StreamingHttpResponse

    其他逻辑不变,主要变化在后端处理

    from django.http import StreamingHttpResponse
    def download(request):
        file=open('crm/models.py','rb')
        response =StreamingHttpResponse(file)
        response['Content-Type']='application/octet-stream'
        response['Content-Disposition']='attachment;filename="models.py"'
        return response
    方式三:使用FileResponse
    from django.http import FileResponse
    def download(request):
        file=open('crm/models.py','rb')
        response =FileResponse(file)
        response['Content-Type']='application/octet-stream'
        response['Content-Disposition']='attachment;filename="models.py"'
        return response
    使用总结

    三种http响应对象在django官网都有介绍.入口:https://docs.djangoproject.com/en/1.11/ref/request-response/

    推荐使用FileResponse,从源码中可以看出FileResponse是StreamingHttpResponse的子类,内部使用迭代器进行数据流传输。

  • 相关阅读:
    python的thread模块作用
    Python2、3解释器inpurt()函数的区别
    python中的单例设计模式
    Python2、3解释器中字符串中的区别
    浏览器向服务器发送请求的请求头解析
    Python中输出函数print()的三个参数
    Python中四种交换两个变量的值的方法
    学习爬虫看着篇(基础篇)
    Python读写txt文件时的编码问题
    网页和自然语言处理中的字符问题(半角和全角)
  • 原文地址:https://www.cnblogs.com/wdliu/p/8723981.html
Copyright © 2011-2022 走看看