XH_Digital_Management/common/views.py

20 lines
751 B
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 00:57:14 +08:00
from django.contrib.staticfiles import finders
from django.http import FileResponse, HttpResponseNotFound
import os
def download_excel_template(request, template_name):
file_path = finders.find(f'excels/{template_name}')
if not file_path:
return HttpResponseNotFound('<h1>文件未找到</h1>')
# 直接创建一个FileResponse不需要先打开文件
response = FileResponse(open(file_path, 'rb'), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
# 使用urllib.parse.quote进行URL编码以确保文件名中的特殊字符被正确处理
response['Content-Disposition'] = f'attachment; filename="{urllib.parse.quote(template_name)}"'
return response