zoukankan      html  css  js  c++  java
  • Django的文件下载

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

    我们这里介绍三种Django下载文件的简单写法,然后使用第三种方式,完成一个高级一些的文件下载的方法

    index.html内容如下

    <div>
        <a href="{% url 'download' %}">文件下载</a>
    </div>

    urls.py文件内容如下:

    urlpatterns = [
    
        url(r'^index/', views.index,name='index'),
        url(r'^download/', views.download,name='download'),
    
    ]

    view视图函数的写法有一下三种:

    方式1:

    复制代码
    from django.shortcuts import HttpResponse
    def download(request):
      file = open('crm/models.py', 'rb') #打开指定的文件
      response = HttpResponse(file)   #将文件句柄给HttpResponse对象
      response['Content-Type'] = 'application/octet-stream' #设置头信息,告诉浏览器这是个文件
      response['Content-Disposition'] = 'attachment;filename="models.py"' #这是文件的简单描述,注意写法就是这个固定的写法
      return response
    复制代码

      注意:HttpResponse会直接使用迭代器对象,将迭代器对象的内容存储城字符串,然后返回给客户端,同时释放内存。可以当文件变大看出这是一个非常耗费时间和内存的过程。而StreamingHttpResponse是将文件内容进行流式传输,数据量大可以用这个方法

    方式2:

    复制代码
    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
    复制代码

    方式3:

    复制代码
    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的子类,内部使用迭代器进行数据流传输。

  • 相关阅读:
    学习js笔记(第3章-语句和严格模式)
    学习js笔记(1,2章)
    学习闭包
    JavaScript 内存泄漏
    jQuery基础(四)—动画篇
    网站性能优化之yahoo军规
    webpack打包vue文件报错:Module parse failed: Unexpected token (1:0)
    PHP图片转为webp格式
    postman在phpstorm使用xdebug调试
    charles抓取手机APP,配置正确却抓不到数据
  • 原文地址:https://www.cnblogs.com/lulin9501/p/11081476.html
Copyright © 2011-2022 走看看