详解Django三种文件下载方式:HttpResponse、StreamingHttpResponse与FileResponse
本文详细介绍Django中实现文件下载的三种主要方式:HttpResponse、StreamingHttpResponse和FileResponse。通过对比源码与适用场景,指出FileResponse作为StreamingHttpResponse子类,利用迭代器处理大文件流传输的优势,并推荐在实际项目中优先使用FileResponse以获得更好的性能与内存管理。
一、概述
在实际的项目开发中,文件下载功能非常常见,例如导出Excel报表、生成PDF文档或提供普通文件下载。虽然你可以搭建独立的资源服务器(如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的子类,内部使用迭代器进行数据流传输。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













