2016-09-07 28 views
0

在yii2項目中,我正在使用組件來下載其路徑保存在我的數據庫中的文件。使用自定義組件下載Yii2文件

我已經設置了下載按鈕,在我的行動列

['class' => 'yii\grid\ActionColumn', 
       'template'=>'{update}{pdf}{delete}', 
       'buttons'=>[ 
        // to display pdf icon. 
        'pdf' => function ($url, $model) {  
           $id = []; 
           foreach ($model->sdsrefs as $mod) 
            $id[] = $mod->file_id; 
            return Html::a('<span class="glyphicon glyphicon-download-alt"></span>', Url::to(['product/download', 'id' => implode($id)]), [ 

            ]);      
          } 
       ], 
       'options'=>[ 
        'style'=>'width:70px;' 
       ] 
    ], 

我已經安裝在上面的代碼鏈接到控制器動作。

我的控制器動作

public function actionDownload($id) 
    { 
     Yii::$app->files->downloadFile($id); 
     $searchModel = new ProductSearch(); 
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams); 


     return $this->render('index', [ 
      'searchModel' => $searchModel, 
      'dataProvider' => $dataProvider, 
     ]); 

    } 

在控制器中的操作,我爲了下載調用的組件。這裏發生的不是下載,當我點擊PDF按鈕時,它會迴應頁面中的內容。當我按下Pdf按鈕時,我希望它執行文件的下載。

我在組件中的下載功能。

public static function downloadFile($id) { 
     $file = File::findOne($id); 
     $filepath = Files::getFilePath($id); 
     if (file_exists($filepath)) { 
      header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
      header('Content-Description: File Transfer'); 
      header('Content-Type: application/octet-stream'); 
      header('Content-Disposition: attachment; filename='.$file->file_name); 
      header('Content-Length: ' . filesize($filepath)); 
      readfile("$filepath"); 
     }else{ 
      echo "file not exist: ".$filepath;    
     } 
     exit; 
    } 

我怎樣才能達到我的結果.i.e下載時,我點擊PDF操作按鈕?

謝謝

回答