python - django 实现文件下载功能


使用 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>

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM