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

时间:2016-08-07 19:11:24

标签: file view upload yii2 display

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

型号:

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(); ?>

提前致谢。

1 个答案:

答案 0 :(得分:1)

更新您的表单视图,如下所示:

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

}
],

],
]); ?>