详解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设计】。

相关文章

详解Python2.x中对Unicode编码的使用

我确定有很多关于Unicode和Python的说明,但为了方便自己的理解使用,我还是打算再写一些关于它们的东西。   字节流 vs Unicode对象 我们先来用Python定...

python 中pyqt5 树节点点击实现多窗口切换问题

python 中pyqt5 树节点点击实现多窗口切换问题

下面通过实例代码给大家介绍python 中pyqt5 树节点点击实现多窗口切换问题,具体代码如下所示: # coding=utf-8 import sys from PyQt5.Qt...

selenium+python自动化测试之鼠标和键盘事件

selenium+python自动化测试之鼠标和键盘事件

前面的例子中,点击事件都是通过click()方法实现鼠标的点击事件。其实在WebDriver中,提供了许多鼠标操作的方法,这些操作方法都封装在ActionChains类中,包括鼠标右击、...

解决Python 中英文混输格式对齐的问题

Python中使用str.format进行格式化输出 format使用方法较多,这里只说明其在填充与对齐上的使用方法: 填充与对齐 填充常跟对齐一起使用 ^、<、>分别是居中...

django将网络中的图片,保存成model中的ImageField的实例

有这样的情形,django个人头像在model中是: class UserProfile(AbstractUser): """ 用户 """ name = models.Ch...