Reputation: 131
I'm very new with YII2. I want to create a download function to the file that was uploaded before. I've referred how to create action download at Gridview in Yii2. However, when I click button download, it load the blank page. Here the code.
At gridview
<?=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']);
}
],
]
]); ?>
At 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);
}
}
At actionCreate (upload file)
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,
]);
}
}
Thanks.
Upvotes: 0
Views: 2805
Reputation: 532
I suspect that the $path is not correct, in the action create, you already include the uploads folder in your $model->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();
....
}
}
but you use it again in actionDownlaod
public function actionDownload($id)
{
.....
$path=Yii::getAlias('@webroot').'/uploads/'.$download->project_file;
if (file_exists($path)) {
return Yii::$app->response->sendFile($path);
}
}
you should try to remove the uploads
folder in the actionDownlaod, and added some debug message
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");
}
}
Upvotes: 4