当前位置:
首页 >
详解django三种文件下载方式
发布时间:2025/3/16
31
豆豆
生活随笔
收集整理的这篇文章主要介绍了
详解django三种文件下载方式
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
推荐使用FileResponse,从源码中可以看出FileResponse是StreamingHttpResponse的子类,内部使用迭代器进行数据流传输。
在实际的项目中很多时候需要用到下载功能,如导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 HttpResponsedef 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 StreamingHttpResponsedef 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转载于:https://www.cnblogs.com/nyist-xsk/p/10155509.html
总结
以上是生活随笔为你收集整理的详解django三种文件下载方式的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 为什么阿里巴巴不允许使用Executor
- 下一篇: 送分题,ArrayList 的扩容机制了