详解django三种文件下载方式

yipeiwu_com6年前Python基础

一、概述

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

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

<div class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >点我下载</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设计】。

相关文章

利用pyinstaller打包exe文件的基本教程

前言 PyInstaller可以用来打包python应用程序,打包完的程序就可以在没有安装Python解释器的机器上运行了。PyInstaller支持Python 2.7和Python...

python类继承与子类实例初始化用法分析

本文实例讲述了python类继承与子类实例初始化用法。分享给大家供大家参考。具体分析如下: [ 先贴参考书籍原文(中文英文对照)] __init__方法介绍: If a base cla...

python根据url地址下载小文件的实例

如下所示: #########start根据url地址下载小文件############ def download_little_file(from_url,to_path): c...

Python找出list中最常出现元素的方法

本文实例讲述了Python找出list中最常出现元素的方法。分享给大家供大家参考,具体如下: 假设一个list中保存着各种元素,需要统计每个元素出现的个数,并打印出最常出现的前三个元素分...

Python文件右键找不到IDLE打开项解决办法

Python文件右键找不到IDLE打开项解决办法

经常会碰到,双击.py文件运行不了,或右键没有IDLE编辑的项,在WIN7系统中比较常见. 双击*.py文件运行不了解决办法: 右键点击 -> 打开方式 -> 选择默认程序...