详解django三种文件下载方式_python


本文摘自php中文网,作者不言,侵删。

这篇文章主要介绍了详解django三种文件下载方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

一、概述

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

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

1

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

方式一:使用HttpResponse

路由url:

1

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

views.py代码

1

2

3

4

5

6

7

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

其他逻辑不变,主要变化在后端处理

1

2

3

4

5

6

7

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

1

2

3

4

5

6

7

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


以上就是详解django三种文件下载方式_python的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python实现的求解最小公倍数算法示例

Python模块之sys模块和序列化模块

基于Python 装饰器装饰类中的方法

Python基础之内置函数和递归详解

电脑上怎么安装Python

值得一看的Python高效数据处理

Python中new类方法和init 实例方法以及单例模式的介绍(附示例)

Python如何筛选序列中的元素

Python自动化运维是干什么的

Python中的【//】是什么运算符号

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...