我对 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);
}
}
在 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,
]);
}
}
谢谢。