首页  >  文章  >  后端开发  >  详解django三种文件下载方式_python

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

不言
不言原创
2018-04-08 11:22:192253浏览

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

一、概述

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

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

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

方式一:使用HttpResponse

路由url:

url(r&#39;^download/&#39;,views.download,name="download"),

views.py代码

from django.shortcuts import HttpResponse
def download(request):
  file = open(&#39;crm/models.py&#39;, &#39;rb&#39;)
  response = HttpResponse(file)
  response[&#39;Content-Type&#39;] = &#39;application/octet-stream&#39; #设置头信息,告诉浏览器这是个文件
  response[&#39;Content-Disposition&#39;] = &#39;attachment;filename="models.py"&#39;
  return response

方式二:使用StreamingHttpResponse

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

from django.http import StreamingHttpResponse
def download(request):
  file=open(&#39;crm/models.py&#39;,&#39;rb&#39;)
  response =StreamingHttpResponse(file)
  response[&#39;Content-Type&#39;]=&#39;application/octet-stream&#39;
  response[&#39;Content-Disposition&#39;]=&#39;attachment;filename="models.py"&#39;
  return response

方式三:使用FileResponse

from django.http import FileResponse
def download(request):
  file=open(&#39;crm/models.py&#39;,&#39;rb&#39;)
  response =FileResponse(file)
  response[&#39;Content-Type&#39;]=&#39;application/octet-stream&#39;
  response[&#39;Content-Disposition&#39;]=&#39;attachment;filename="models.py"&#39;
  return response

使用总结

三种http响应对象在django官网都有介绍.入口:https://docs.djangoproject.com/en/1.11/ref/request-response/

推荐使用FileResponse,从源码中可以看出FileResponse是StreamingHttpResponse的子类,内部使用迭代器进行数据流传输。


以上是详解django三种文件下载方式_python的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn