详解Django关于StreamingHttpResponse与FileResponse文件下载的最优方法
作者:Better_Zflyee 时间:2021-04-13 08:17:01
1 StreamingHttpResponse下载
StreamingHttpResponse(streaming_content):流式相应,内容的迭代器形式,以内容流的方式响应。
注:StreamingHttpResponse一般多现实在页面上,不提供下载。
以下为示例代码
def streamDownload(resquest):
def file_iterator(filepath, chunk_size = 512):
with open(filepath, 'rb') as f:
while True:
con = f.read(512)
if con:
yield con
else:
break
filename = os.path.abspath(__file__) + 'test.txt'
response = StreamingHttpResponse(file_iterator(filename)
return response
# 最后程序会将结果打印在显示器上
2 FileResponse下载
FileResponse(stream):以流形式打开后的文件
注:FileResponse是StreamingHttpResponse的子类
以下为示例代码:
def homeproc2(request):
cwd = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
response = FileResponse(open(cwd + "/msgapp/templates/youfile", "rb"))
response['Content-Type] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="filename"'
return response
需要解释说明的是:
response['Content-Type] = 'application/octet-stream'
response['COntent-Disposition'] = 'attachment;filename="filename"'
Content-Type:用于指定文件类型。
COntent-Disposition:用于指定下载文件的默认名称,对,没错! “CO”两个字符都要大写。
两者都是MIME协议里面的标准类型。
来源:https://blog.csdn.net/Geoffrey_Zflyee/article/details/107360761
标签:Django,StreamingHttpResponse,FileResponse,下载
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
聚族索引、非聚族索引、组合索引的含义和用途
2010-07-02 21:51:00
不同操作系统下的mysql数据库同步
2008-12-22 14:41:00
asp开发中textarea常见问题
2008-04-13 06:34:00
Python Pandas对缺失值的处理方法
2021-03-18 19:38:55
人工智能学习Pytorch张量数据类型示例详解
2021-09-13 01:33:08
![](https://img.aspxhome.com/file/2023/5/72795_0s.png)
无级分类的多级联动
2020-07-02 12:53:12
教你用Python实现一个轮盘抽奖小游戏
2021-11-04 23:49:03
![](https://img.aspxhome.com/file/2023/6/71406_0s.jpg)
Django model 中设置联合约束和联合索引的方法
2023-09-24 09:14:15
精简版的MySQL制作步骤
2011-03-08 09:52:00
pjblog3相关日志功能(支持生成静态模式)
2008-11-20 13:41:00
Mootools 1.2教程(14)——定时器和哈希简介
2008-12-08 12:50:00
PHP抽象工厂模式Abstract Factory Pattern优点与实现方式
2023-05-25 03:04:57
Highcharts 图表中图例显示状态存储的功能设计详解
2023-05-30 02:01:09
Python实现自动化处理PDF文件的方法详解
2024-01-02 07:02:21
![](https://img.aspxhome.com/file/2023/5/70745_0s.jpg)
20行python代码的入门级小游戏的详解
2023-07-15 01:25:31
background-clip/origin一则运用
2008-04-15 14:45:00
![](https://img.aspxhome.com/file/UploadPic/20084/15/2008415145225878s.png)
使用ASP调用C#写的COM组件
2010-04-03 20:45:00
HTML5本地存储初探(三)
2010-03-07 15:49:00
![](https://img.aspxhome.com/file/UploadPic/20103/7/20100131-mheq73uiue19x7q5g9c52ngtwm-29s.png)
Linux安装Python3如何和系统自带的Python2并存
2023-08-25 03:42:09
ASP分页函数
2009-07-06 12:41:00