• Django学习之文件下载


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

  • 相关阅读:
    SQL Server 损坏修复
    记录一些数据库函数或全局变量
    查询数据库空间使用情况
    SQL Server 2008文件与文件组的关系
    大型网站--负载均衡架构
    本地事务和分布式事务工作实践
    IIS防止同一IP大量非法访问
    使用EventLog类写Windows事件日志
    1878: [SDOI2009]HH的项链
    模板
  • 原文地址:https://www.cnblogs.com/ciquankun/p/11711363.html
Copyright © 2020-2023  润新知