国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

詳解django三種文件下載方式

2020-02-22 23:36:50
字體:
供稿:網(wǎng)友

一、概述

在實(shí)際的項(xiàng)目中很多時(shí)候需要用到下載功能,如導(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 HttpResponsedef download(request):  file = open('crm/models.py', 'rb')  response = HttpResponse(file)  response['Content-Type'] = 'application/octet-stream' #設(shè)置頭信息,告訴瀏覽器這是個(gè)文件  response['Content-Disposition'] = 'attachment;filename="models.py"'  return response

方式二:使用StreamingHttpResponse

其他邏輯不變,主要變化在后端處理

from django.http import StreamingHttpResponsedef 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 FileResponsedef 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

使用總結(jié)

三種http響應(yīng)對(duì)象在django官網(wǎng)都有介紹.入口:https://docs.djangoproject.com/en/1.11/ref/request-response/

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

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

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 武邑县| 大余县| 黑水县| 望谟县| 达孜县| 同江市| 黑水县| 涟水县| 江川县| 阿拉善右旗| 嘉黎县| 娱乐| 武夷山市| 桐城市| 河北区| 浦县| 渝北区| 桓台县| 庆安县| 拉孜县| 乌海市| 化德县| 仪陇县| 凤城市| 玉林市| 绥宁县| 温宿县| 阿克陶县| 寻乌县| 利川市| 黄陵县| 区。| 青岛市| 长寿区| 铁岭市| 遵义县| 敦化市| 阿巴嘎旗| 云阳县| 思南县| 大竹县|