Django 如何實現文件下載


1. 思路:

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

2. a標簽實現

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

3. 設置響應頭

方法一:使用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 

方法二:使用StreamingHttpResponse

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 

總結:對比

雖然使用這三種方式都能實現,但是推薦用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. 項目案例:

1.讓公司內部可以批量導入客戶資源信息;

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

增加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視圖函數:

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>

 

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM