python - django implementation file download function

Add a site built using the Django can download a file from the server (here to download a demo from the site of the API documentation examples for reference)

 

# One. url 

 

= the urlpatterns [ 
 
   # download API interface document 
    re_path ( '^ index / api_download /', home.DownLoadApiView, name = "downloads"), 

]

 

 

# II. views

DownLoadApiView DEF (Request): 
    "" " 
        API documentation Download 
    : param Request: 
    : return: 
    " "" 
    IF request.method == "GET": 
        File = Open ( 'static / api_document / api.pdf', 'rb') 
        the Response = HttpResponse (file) 
        the Response [ 'Content-Type'] = 'the Application / OCTET-Stream' # set header information that tells the browser this is a file 
        response [ 'Content-Disposition'] = 'attachment; filename = "api. PDF " ' 
        return Response

  

 

# three. The front page add tags

<a href="{% url'download' %}"> Download API documentation </a>

  

Guess you like

Origin www.cnblogs.com/chaoqi/p/11114214.html