• Django_文件下载


    一、小文件下载

    1、视图 views.py

    三种方式实现,任选其一

    (1)使用HttpResponse

    # 导入模块
    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

    (2)使用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

    (3)使用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

    2、添加路由 urls.py

    配置一个下载的路径

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

    3、模板 templates 的修改

    配置一个 a 标签,跳转地址配置要跳转的下载路径(对应的视图)

    <div class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >点我下载</a></div>

    二、大文件下载

    大文件需要使用迭代器优化

    只需要修改 views.py 文件

    from django.http import StreamingHttpResponse
    
    def download(request):
      def file_iterator(file_name, chunk_size=512):
         with open(file_name, 'rb') as f:
            while True:
               c = f.read(chunk_size)
                  if c:
                     yield c
                   else:
                      break
       the_file_name = 'static/images/exam/logo.png'
       response = StreamingHttpResponse(file_iterator(the_file_name))
       response['Content-Type'] = 'application/octet-stream'
       response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
       return response

     

  • 相关阅读:
    整合了一个命令行程序的框架
    CentOS下mysql数据库data目录迁移和配置优化
    关于华硕主板的图像输出设置
    在jetson tx1下编译安装opencv3.2的一点小总结
    安装pydev 但是没有pydev工程选项
    关于PID控制的认识
    notebook( office + matlab)
    vmware 后台运行不能恢复
    将必应设置成chrome的默认搜索引擎
    centOS 7 apache 不能访问
  • 原文地址:https://www.cnblogs.com/yebaofang/p/12095959.html
Copyright © 2020-2023  润新知