在gridview yii2中下载动作

时间:2016-10-29 08:38:44

标签: yii2 yii2-advanced-app yii2-user

我对YII2很新。我想为之前上传的文件创建一个下载功能。我已经提到了如何在Yii2中的Gridview创建动作下载。但是,当我单击按钮下载时,它会加载空白页面。这是代码。

在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']);

        }
        ],
            ]

]);  ?&GT;

在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);

}
}

在actionCreate(上传文件)

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,
            ]);
            }         

}

感谢。

1 个答案:

答案 0 :(得分:2)

我怀疑$ path不正确,在动作创建中,您已经在 $ model-&gt; 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();
            ....
     }         

}

但您在 actionDownlaod

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

    }
}

您应该尝试删除 actionDownlaod 中的uploads文件夹,并添加一些调试消息

    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");
        }
    }