Django 實現文件下載

1. 思路:html

文件,讓用戶下載
    - a標籤+靜態文件
    - 設置響應頭(django如何實現文件下載)

2. a標籤實現前端

<a href="/static/xxx.xlsx">下載模板</a>

3. 設置響應頭django

方法一:使用HttpResponse緩存

複製代碼
from django.shortcuts import HttpResponse  
def file_down(request):  
    file=open('/home/amarsoft/download/example.tar.gz','rb')  
    response =HttpResponse(file)  
    response['Content-Type']='application/octet-stream'  
    response['Content-Disposition']='attachment;filename="example.tar.gz"'  
    return response 
複製代碼

方法二:使用StreamingHttpResponseapp

複製代碼
from django.http import StreamingHttpResponse  
def file_down(request):  
    file=open('/home/amarsoft/download/example.tar.gz','rb')  
    response =StreamingHttpResponse(file)  
    response['Content-Type']='application/octet-stream'  
    response['Content-Disposition']='attachment;filename="example.tar.gz"'  
    return response  
複製代碼

方法三:使用FileResponse函數

複製代碼
from django.http import FileResponse  
def file_down(request):  
    file=open('/home/amarsoft/download/example.tar.gz','rb')  
    response =FileResponse(file)  
    response['Content-Type']='application/octet-stream'  
    response['Content-Disposition']='attachment;filename="example.tar.gz"'  
    return response 
複製代碼

總結:對比url

1
2
3
雖然使用這三種方式都能實現,可是推薦用FileResponse,在FileResponse中使用了緩存,更加節省資源。雖然說是三種方式,可是原理相同,說白了就是一種方式。爲了更好的實現文件下載,FileResponse對StreamingHttpResponse作了進一步的封裝,即StreamingHttpResponse是FileResponse的父類。而HttpResponse,StreamingHttpResponse,FileResponse三者都繼承了基類HttpResponseBase。HttpResponseBase類是一個字典類,其封裝了一個_headers屬性,該屬性是一個字典類型,裏面封裝了response的頭信息。由於該HttpResponseBase類被封裝成了一個字典類,因此能夠直接使用response[ 'Content-Type' ]這種形式訪問,也可使用response._headers[ 'Content-Type' ]訪問。值得注意的是:
1.HttpResponseBase只有來設置response的頭信息,並不能返回給客戶端發生數據。
2.response.keys()這中形式不能訪問到字典的方法,必須使用response._headers.keys()才能訪問到字典的方法。

 

4. 項目案例:spa

1.讓公司內部能夠批量導入客戶資源信息;code

2. 首先要下載xlsx模板文件;orm

增長URL:

 

urlpatterns = [
    url(r'^stark/crm/login/', crm_views.login,name='crm_login'),
    url(r'^stark/crm/index/', crm_views.index,name='crm_index'),
    url(r'^stark/crm/Download/', crm_views.download,name='crm_download'),
]

編寫download視圖函數:

1
2
3
4
5
6
def download(request):
     file=open( 'static/xlsx/xlsx_file.xlsx' , 'rb' )
     response =FileResponse(file)
     response[ 'Content-Type' ]= 'application/octet-stream'
     response[ 'Content-Disposition' ]= 'attachment;filename="xlsx_file.xlsx"'
     return  response

前端頁面反向解析URL

複製代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>批量導入客戶數據</title>
</head>
<body>

<h2>批量導入</h2>
<form action="">
    <a href="{% url 'crm_download' %}">下載模板</a>
    <p><input type="file" name="xsfile"></p>
    <p><input type="submit" value="提交"></p>
</form>


</body>
</html>
複製代碼
相關文章
相關標籤/搜索