詳解django三種文件下載方式

推薦使用FileResponse,從源碼中能夠看出FileResponse是StreamingHttpResponse的子類,內部使用迭代器進行數據流傳輸。python

在實際的項目中不少時候須要用到下載功能,如導excel、pdf或者文件下載,固然你可使用web服務本身搭建能夠用於下載的資源服務器,
如nginx,這裏咱們主要介紹django中的文件下載。
實現方式:a標籤+響應頭信息(固然你能夠選擇form實現)
<div class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >點我下載</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' #設置頭信息,告訴瀏覽器這是個文件
              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
相關文章
相關標籤/搜索