詳解django三種文件下載方式
一、概述
在實際的項目中很多時候需要用到下載功能,如導excel、pdf或者文件下載,當然你可以使用web服務自己搭建可以用于下載的資源服務器,如nginx,這里我們主要介紹django中的文件下載。
實現方式:a標簽+響應頭信息(當然你可以選擇form實現)
<div class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >點我下載</a></div>
方式一:使用HttpResponse
路由url:
url(r'^download/',views.download,name="download"),
views.py代碼
from django.shortcuts import HttpResponse
def download(request):
file = open('crm/models.py', 'rb')
response = HttpResponse(file)
response['Content-Type'] = 'application/octet-stream' #設置頭信息,告訴瀏覽器這是個文件
response['Content-Disposition'] = 'attachment;filename="models.py"'
return response
方式二:使用StreamingHttpResponse
其他邏輯不變,主要變化在后端處理
from django.http import StreamingHttpResponse
def download(request):
file=open('crm/models.py','rb')
response =StreamingHttpResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="models.py"'
return response
方式三:使用FileResponse
from django.http import FileResponse
def download(request):
file=open('crm/models.py','rb')
response =FileResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="models.py"'
return response
使用總結
三種http響應對象在django官網都有介紹.入口:https://docs.djangoproject.com/en/1.11/ref/request-response/
推薦使用FileResponse,從源碼中可以看出FileResponse是StreamingHttpResponse的子類,內部使用迭代器進行數據流傳輸。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python Numpy運行報錯:IndexError: too many in
在使用Numpy進行數組操作時,經常會遇到各種錯誤,其中,IndexError: too many indices for array是一種常見的錯誤,它通常發(fā)生在嘗試使用一個過多維度的索引來訪問一個較低維度的數組時,本文介紹了Python Numpy報錯的解決辦法,需要的朋友可以參考下2024-07-07

