一、概述
在实际的项目中很多时候需要用到下载功能,如导excel、pdf或者文件下载,当然你可以使用web服务自己搭建可以用于下载的资源服务器,如nginx,这里我们主要介绍django中的文件下载。
实现方式:a标签+响应头信息(当然你可以选择form实现)
<p class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >点我下载</a></p>
方式一:使用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
以上就是详解django三种文件下载方式_python的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于详解django三种文件下载方式_python的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did84236