背景: 我需要实现用户上传excel并批量提交到数据库的功能。我需要首先实现文件下载功能,让用户下载excel样例。
前端:
<a href="{% url 'download_data' %}">上传模板.xlsx</a>
urls.py:
urlpatterns = [
url(r'^download_data', views.download_data, name='download_data')
]
views.py:
def download_hospital(request):
filename = 'static/resource/模板.xlsx' # 要下载的文件路径 注意别用../static 这样的
response = StreamingHttpResponse(readFile(filename))
response['Content-Type'] = 'application/octet-stream'
# 用这条不适用按中文文件名
# response['Content-Disposition'] = 'attachment;filename= 上传-模板.xlsx'
response['Content-Disposition'] = 'attachment;filename= '+'上传-模板'.encode('utf-8').decode('ISO-8859-1')+'.xlsx'
return response
# 读文件
def readFile(filename, chunk_size=512):
with open(filename, 'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
功能ok,再把前端的<a>标签稍微美化一下: