XH_Digital_Management/common/views.py

35 lines
1.5 KiB
Python
Raw Normal View History

2024-06-01 00:57:14 +08:00
import urllib.parse
2024-05-30 17:06:23 +08:00
2024-06-01 01:40:12 +08:00
from django.contrib.auth.decorators import login_required
2024-06-01 00:57:14 +08:00
from django.contrib.staticfiles import finders
from django.http import FileResponse, HttpResponseNotFound
2024-06-01 01:40:12 +08:00
@login_required
2024-06-01 00:57:14 +08:00
def download_excel_template(request, template_name):
2024-06-01 01:40:12 +08:00
"""
该视图提供下载指定的Excel模板文件
2024-06-01 00:57:14 +08:00
2024-06-01 01:40:12 +08:00
参数:
request: HttpRequest对象
template_name: 请求下载的Excel模板文件的名称期望是一个字符串
返回:
FileResponse对象允许用户下载指定的Excel模板文件
如果文件未找到则返回一个HttpResponseNotFound响应
"""
# 使用finders.find()根据文件名在Django的静态文件目录中查找文件的绝对路径
2024-06-01 00:57:14 +08:00
file_path = finders.find(f'excels/{template_name}')
2024-06-01 01:40:12 +08:00
# 如果文件路径不存在返回404响应
2024-06-01 00:57:14 +08:00
if not file_path:
return HttpResponseNotFound('<h1>文件未找到</h1>')
2024-06-01 01:40:12 +08:00
# 创建FileResponse对象设置为以附件形式下载设置MIME类型为Excel文件
response = FileResponse(open(file_path, 'rb'),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
# 设置Content-Disposition头告诉浏览器这是一个需要下载的文件
# 使用urllib.parse.quote对文件名进行URL编码以确保文件名中包含的特殊字符不会引起问题
2024-06-01 00:57:14 +08:00
response['Content-Disposition'] = f'attachment; filename="{urllib.parse.quote(template_name)}"'
return response