使用 Django 搭建的网站中添加一个可以从服务器中下载文件的功能 (此处演示一个从网站中下载API文档的例子供参考)
# 一。url
urlpatterns = [ # 下载 API 接口文档 re_path('^index/api_download/', home.DownLoadApiView, name="download"), ]
# 二。views
def DownLoadApiView(request): """ API文档下载 :param request: :return: """ if request.method == "GET": file = open('static/api_document/api.pdf', 'rb') response = HttpResponse(file) response['Content-Type'] = 'application/octet-stream' # 设置头信息,告诉浏览器这是个文件 response['Content-Disposition'] = 'attachment;filename="api.pdf"' return response
# 三。前端页面中添加标签
<a href="{% url 'download' %}">点击下载API文档</a>