2016-10-29 11 views
0

私はYII2でとても新しいです。以前にアップロードされたファイルにダウンロード機能を作成したい。私はYii2のGridviewでアクションダウンロードを作成する方法を紹介しました。ただし、ボタンのダウンロードをクリックすると空白のページが読み込まれます。ここにコード。 GridViewの時アクションダウンロードでgridview yii2

<?=GridView::widget([ 
     'dataProvider'=>$dataProvider, 
     'id'=>'mygrid', 
     'columns' => [ 
     ['class' => 'yii\grid\SerialColumn'], 
     'project_name', 
     'project_file', 
     'created_date', 
     [ 
     'class' => 'yii\grid\ActionColumn', 
     ], 
     ['attribute'=>'Download', 
     'format'=>'raw', 
     'value' => function($data) 
     { 
     return 
     Html::a('Download file', ['firstyear/download', 'id' => $data->id],['class' => 'btn btn-primary']); 

     } 
     ], 
      ] 

])。 actionCreate(アップロードファイル)でactionDownload

public function actionDownload($id) 
{ 
$download = Firstyear::findOne($id); 
$path=Yii::getAlias('@webroot').'/uploads/'.$download->project_file; 
if (file_exists($path)) { 

    return Yii::$app->response->sendFile($path); 

} 
} 

で ?>

public function actionCreate() 
{ 
    $model = new Firstyear(); 
    if ($model->load(Yii::$app->request->post())) 
    {  
      $project =$model->project_name; 
      $model->file= UploadedFile::getInstance($model,'file'); 
      $model-> file->saveAs('uploads/'.$project.'.'.$model->file->extension); 
      $model->project_file='uploads/'.$project.'.'.$model->file->extension; 

      $model->save(); 
      Yii::$app->getSession()->setFlash('success','Data saved!'); 
      return $this->redirect(['view','id'=> $model->id]); 
      } 

      else { 

      return $this ->renderAjax('create', [ 
       'model'=>$model, 
      ]); 
      }   

} 

感謝。

答えて

2

私は$パスが作成、あなたはすでにあなたの$モデル - > project_file

public function actionCreate() 
{ 
    $model = new Firstyear(); 
    if ($model->load(Yii::$app->request->post())) 
    {  
      ....... 
      $model->project_file='uploads/'.$project.'.'.$model->file->extension; 
      $model->save(); 
      .... 
    }   

} 

いますが、で再びそれを使用中アップロードフォルダが含まれるアクションで、正しくないと思われます

public function actionDownload($id) 
{ 
    ..... 
    $path=Yii::getAlias('@webroot').'/uploads/'.$download->project_file; 
    if (file_exists($path)) { 
     return Yii::$app->response->sendFile($path); 

    } 
} 

actionDownlaodあなたは行為でuploadsフォルダを削除しようとする必要がありますionDownlaodを追加し、デバッグメッセージを追加しました

public function actionDownload($id) 
    { 
     ..... 
     $path=Yii::getAlias('@webroot').'/'.$download->project_file; 
     if (file_exists($path)) { 
      return Yii::$app->response->sendFile($path); 
     } else { 
      throw new NotFoundHttpException("can't find {$download->project_file} file"); 
     } 
    } 
+0

ありがとうございました。できます! @David – Fyp16

+0

ようこそ。私はそれがうまく働いた – David

関連する問題