django三种文件下载方式

前端之家收集整理的这篇文章主要介绍了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[] = 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(,=]=]= response
方式三:使用FileResponse django.http =open(,=]=]= 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的子类,内部使用迭代器进行数据流传输。

猜你在找的Django相关文章