一周学会Django5 Python Web开发-Django5二进制文件下载响应

本文介绍了Django5中实现文件下载功能的三种方式:HttpResponse、StreamingHttpResponse和FileResponse,通过示例展示了如何在views.py中创建和在urls.py中映射这些下载链接,以及在HTML页面上测试下载功能。
摘要由CSDN通过智能技术生成

锋哥原创的Python Web开发 Django5视频教程:

2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~共计25条视频,包括:2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~、第2讲 Django5安装、第3讲 Django5创建项目(用命令方式)等,UP主更多精彩视频,请关注UP账号。icon-default.png?t=N7T8https://www.bilibili.com/video/BV14Z421z78C/响应内容除了返回网页信息外,还可以实现文件下载功能,是网站常用的功能之一。

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

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

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

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

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

我们准备一个文件,这里我们用一个exe二进制文件。放D盘根目录。

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

# 定义文件路径
file_path = "D:\\360zip_setup.exe"


def download_file1(request):
    file = open(file_path, 'rb')  # 打开文件
    response = HttpResponse(file)  # 创建HttpResponse对象
    response['Content_Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename=file1.exe'
    return response


def download_file2(request):
    file = open(file_path, 'rb')  # 打开文件
    response = StreamingHttpResponse(file)  # 创建StreamingHttpResponse对象
    response['Content_Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename=file2.exe'
    return response


def download_file3(request):
    file = open(file_path, 'rb')  # 打开文件
    response = FileResponse(file)  # 创建FileResponse对象
    response['Content_Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename=file3.exe'
    return response

urls.py里定义下映射:

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">下载测试一:HttpResponse</a><br>
<a href="/download2">下载测试二:StreamingHttpResponse</a><br>
<a href="/download3">下载测试三:FileResponse</a>
</body>
</html>

页面输入:http://127.0.0.1:8000/static/download.html 测试:

分别点击下载测试:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值