python测试开发django-112.文件下载功能
前言
开发一个文件下载功能,在页面上点下载按钮,可以下载一个文件,如excel,word,pdf等
前端模板
前端页面写一个a标签,href地址对应接口下载接口地址:/downpdf
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>down file</title>
</head>
<body>
<h3>下载文件功能开发</h3>
<a href="/downpdf">点我下载</a>
</body>
</html>
待下载的文件放到static目录,如:python1.pdf
views.py视图函数
下载文件使用FileResponse,添加返回头部参数Content-Type和Content-Disposition
from MyDjango.settings import BASE_DIR
from django.views import View
from django.http import FileResponse, HttpResponse
import os
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
class DownPage(View):
def get(self, request):
"""访问web页面"""
return render(request, 'downfile.html')
class DownPDF(View):
def get(self, request):
"""下载pdf接口"""
# 文件路径
file_path = os.path.join(BASE_DIR, 'static', "python1.pdf")
print("11111111111111111111111")
print(file_path)
file = open(file_path, 'rb')
response = FileResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="python1.pdf"'
return response
路由设置
urls.py设置网页访问地址和文件下载地址
urlpatterns = [
url('^down$', views.DownPage.as_view()),
url('^downpdf$', views.DownPDF.as_view())
]
页面效果
web页面访问
点击下载效果
在浏览器直接访问下载地址http://localhost:8000/downpdf
也可以下载
文件名称带中文
下载的文件名称带中文的时候,需要转码,转成ISO-8859-1编码
response = FileResponse(file)
response['Content-Type'] = 'application/octet-stream'
att = 'attachment; filename=python悠悠1.pdf.exe'
response['Content-Disposition'] = att.encode('utf-8', 'ISO-8859-1')
return response
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-09-02 pytest文档50-命令行参数--durations统计用例运行时间
2020-09-02 pytest文档49-命令行参数--tb的使用