1. 程式人生 > >Django 如何實現檔案下載

Django 如何實現檔案下載

我們的目的是下載檔案儲存到磁碟,有些瀏覽器可能直接解析我們的內容並開啟。
為了防止這種情況,需要對響應頭做處理目的告訴瀏覽器接收資料儲存到磁碟
from django.http import FileResponse
	    def down_file(self,request):
	        file = open("F:\Django_project\static\ExcelTemplate.xlsx","rb")
	        response=FileResponse(file)
	        response['Content-Type'] = 'application/octet-stream'
	        response['Content-Disposition'] = 'attachment;filename="Excel.xlsx"'
	        return response