簡單瞭解django檔案下載方式
阿新 • • 發佈:2020-02-11
這篇文章主要介紹了簡單瞭解django三種檔案下載方式,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
推薦使用FileResponse,從原始碼中可以看出FileResponse是StreamingHttpResponse的子類,內部使用迭代器進行資料流傳輸。
在實際的專案中很多時候需要用到下載功能,如導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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。