在 gridview yii2 中下载动作

action download in gridview yii2

我对 YII2 很陌生。我想为之前上传的文件创建一个下载功能。我已经提到了如何在 Yii2 的 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']);

        }
        ],
            ]

]); ?>

正在下载

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

}

谢谢。

我怀疑 $path 不正确,在创建操作中,您已经在 $model->[=28 中包含了 uploads 文件夹=]

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