Django的文件下载
生活随笔
收集整理的這篇文章主要介紹了
Django的文件下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在實際的項目中很多時候需要用到下載功能,如導excel、pdf或者文件下載,當然你可以使用web服務自己搭建可以用于下載的資源服務器,如nginx,這里我們主要介紹django中的文件下載。
我們這里介紹三種Django下載文件的簡單寫法,然后使用第三種方式,完成一個高級一些的文件下載的方法
index.html內容如下
<div><a href="{% url 'download' %}">文件下載</a> </div>urls.py文件內容如下:
urlpatterns = [url(r'^index/', views.index,name='index'),url(r'^download/', views.download,name='download'),]view視圖函數的寫法有一下三種:
方式1:
from django.shortcuts import HttpResponse def download(request):file = open('crm/models.py', 'rb') #打開指定的文件response = HttpResponse(file) #將文件句柄給HttpResponse對象response['Content-Type'] = 'application/octet-stream' #設置頭信息,告訴瀏覽器這是個文件response['Content-Disposition'] = 'attachment;filename="models.py"' #這是文件的簡單描述,注意寫法就是這個固定的寫法return response注意:HttpResponse會直接使用迭代器對象,將迭代器對象的內容存儲城字符串,然后返回給客戶端,同時釋放內存。可以當文件變大看出這是一個非常耗費時間和內存的過程。而StreamingHttpResponse是將文件內容進行流式傳輸,數據量大可以用這個方法
方式2:
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方式3:
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的子類,內部使用迭代器進行數據流傳輸。
轉載于:https://www.cnblogs.com/lulin9501/p/11081476.html
總結
以上是生活随笔為你收集整理的Django的文件下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Docker安装mysql8
- 下一篇: day2笔记