django實現客戶端文件下載

基於django項目,因爲不是專門講文件的下載,這裏僅是項目須要,因此可能不是特別的詳細。僅作流程的演示:前端

實現過程:django

一、準備下載url服務器

 # 下載文件
    url(r'^download_file/$', downloadFile.DownloadFile.as_view(), name='download_file'),

二、視圖類(部分代碼)app

from django.http import FileResponse
class DownloadFile(View,Excel):
    '''
    實現客戶端從服務器端下載文件
    '''
    def get(self,request):
        '''
        將Excel文件發送給客戶端,客戶端進行下載。
        :param request:
        :return:
        '''
        # 一、獲取要寫入Excel表中的數據
        records = self.get_records()
        # 二、服務器先生成Excel數據,並保存在本地
        file_path = self.wite_to_excel('test',records)
        # 三、將數據以流的方式發給客戶端
        file = open(file_path, 'rb')
        response = FileResponse(file)
        # 3.1設置響應頭,客戶端下載文件到本地
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = f'attachment;filename={os.path.basename(file_path)}'
        return response

 上述代碼咱們只從第三步開始看便可,第三步上面是我要發送的數據(Excel數據),你根據本身的實際狀況準備要發送的數據,而後執行第三步使用open函數以二進制的方式讀取文件等接着往下執行便可。函數

三、前端頁面(部份內容)url

<a href="{% url 'download_file' %}" class="btn btn-sm btn-success pull-right">導出數據</a>

 

四、最終我項目的效果以下所示。spa

相關文章
相關標籤/搜索