微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

django三种文件下载方式

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0"><tr>
<td><span style="font-size: 16px;">一、概述</td>
</tr></table>

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

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

<点我下载

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0"><tr>
<td><span style="font-size: 16px;">方式一:使用HttpResponse</td>
</tr></table>

路由url:

url(r,views.download,name=),

views.py代码

django.shortcuts = open(,=] = 文件 response[disposition] = response

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0"><tr>
<td><span style="font-size: 16px;">方式二:使用StreamingHttpResponse</td>
</tr></table>

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

django.http =open(,=]=disposition]= response
方式三:使用FileResponse django.http =open(,=]=disposition]= response

<table style="height: 30px; background-color: #afeeee; width: 1266px; ; width: 1266px;" border="0">

<tr>
<td><span style="font-size: 16px;">使用总结</td>
</tr></table>

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐