溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

簡單了解django文件下載方式

發(fā)布時間:2020-09-20 02:17:18 來源:腳本之家 閱讀:213 作者:xushukui 欄目:開發(fā)技術(shù)

這篇文章主要介紹了簡單了解django三種文件下載方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

推薦使用FileResponse,從源碼中可以看出FileResponse是StreamingHttpResponse的子類,內(nèi)部使用迭代器進(jìn)行數(shù)據(jù)流傳輸。

在實(shí)際的項(xiàng)目中很多時候需要用到下載功能,如導(dǎo)excel、pdf或者文件下載,當(dāng)然你可以使用web服務(wù)自己搭建可以用于下載的資源服務(wù)器,

如nginx,這里我們主要介紹django中的文件下載。

實(shí)現(xiàn)方式:a標(biāo)簽+響應(yīng)頭信息(當(dāng)然你可以選擇form實(shí)現(xiàn))

<div class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >點(diǎn)我下載</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' #設(shè)置頭信息,告訴瀏覽器這是個文件
       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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI