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