系列文章目录
第五章 二进制文件下载响应
前言
这章说一下如何文件下载
响应内容除了返回网页信息外,还可以实现文件下载功能,是网站常用的功能之一。
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 测试:
总结
本章介绍了三种文件下载方式,后续遇到文件下载的代码,可随时来查阅。