【Django5】二进制文件下载响应

系列文章目录

第五章 二进制文件下载响应



前言

这章说一下如何文件下载


响应内容除了返回网页信息外,还可以实现文件下载功能,是网站常用的功能之一。

Django提供三种方式实现文件下载功能,分别是HttpResponse、StreamingHttpResponse和 FileResponse,三者的说明如下:

HttpResponse是所有响应过程的核心类,它的底层功能类是HttpResponseBase。

StreamingHttpResponse是在 HttpResponseBase的基础上进行继承与重写的,它实现流式响应输出(流式响应输出是使用Python的迭代器将数据进行分段处理并传输的),适用于大规模数据响应和文件传输响应。

FileResponse是在StreamingHttpResponse 的基础上进行继承与重写的,它实现文件的流式响应输出,只适用于文件传输响应。

我们通过实例来看下如何应用:

我们准备一个文件,这里我们用一个exe二进制文件。放D盘根目录。
在这里插入图片描述

views.py里写方法实现方法:

def download_file1(request):
    file = open(file_path, 'rb')
    response = HttpResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="SteamSetup1.exe"'
    return response

def download_file2(request):
    file = open(file_path, 'rb')
    response = StreamingHttpResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="SteamSetup2.exe"'
    return response

def download_file3(request):
    file = open(file_path, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="SteamSetup3.exe"'
    return response

urls.py里定义下映射:

urlpatterns = [
    path('download1', helloWorld.views.download_file1),
    path('download2', helloWorld.views.download_file2),
    path('download3', helloWorld.views.download_file3),

]

static目录下新建一个download.html静态文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>下载咯</title>
</head>
<body>
<a href="/download1"> 下载测试1,HttpResponse </a><br>
<a href="/download2"> 下载测试2,StreamingHttpResponse </a><br>
<a href="/download3"> 下载测试3,FileResponse </a>
</body>
</html>

页面输入:http://127.0.0.1:8000/static/download.html 测试:
在这里插入图片描述

总结

本章介绍了三种文件下载方式,后续遇到文件下载的代码,可随时来查阅。

  • 14
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值