如何在 yii2 视图中显示上传的文件并与之交互?

how to display uploaded file in yii2 views and interact with it?

我的控制器添加了文件上传功能,文件存储在指定的目录中,但是update、index、view等视图只显示文件名。我需要一个 link 或一个按钮来与这个上传的文件进行交互。例如,通过按此 link 或按钮打开文件,同时下载此文件。你能帮我吗?

型号:

public function rules()
{
    return [
    ...
        [['attachment'],'file'],
    ];
}

控制器:

public function actionCreate()
{
    $model = new Letter();

    if ($model->load(Yii::$app->request->post())) {
        $model->attachment = UploadedFile::getInstance($model, 'attachment');

        $filename = pathinfo($model->attachment , PATHINFO_FILENAME);
        $ext = pathinfo($model->attachment , PATHINFO_EXTENSION);

        $newFname = $filename.'.'.$ext;

        $path=Yii::getAlias('@webroot').'/uploads/';
        if(!empty($newFname)){
            $model->attachment->saveAs($path.$newFname);
            $model->attachment = $newFname;
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }
    }
    return $this->render('create', [
        'model' => $model,
    ]);

表单视图:

<?php $form = ActiveForm::begin(['options' => ['enctype'=>'multipart/form-data']]); ?>
...

<?= $form->field($model, 'attachment')->fileInput() ?>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

提前致谢。

像下面这样更新您的表单视图:

<?php $form = ActiveForm::begin(['options' => ['enctype'=>'multipart/form-data']]); ?>
...

<?= $form->field($model, 'attachment')->fileInput() ?>

 /*link to download file*/
<?if(!$model->isNewRecord):?>
<?= Html::a('Download file', ['download', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?endif;?>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>


<?php ActiveForm::end(); ?>

在您的控制器中添加新的下载文件操作:

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

    if (file_exists($path)) {
        return Yii::$app->response->sendFile($path);
    }
}

在您的网格视图中:

 <?= GridView::widget([
'dataProvider' => $dataProvider,
'id'=>'mygrid',
'columns' => [
['class' => 'yii\grid\SerialColumn'],



[
'attribute'=>'attachment',
'format'=>'raw',
'value' => function($data)
{
    return
    Html::a('Download file', ['letter/download', 'id' => $data->id], ['class' => 'btn btn-primary']);

}
],

],
]); ?>