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



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

型号:

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' => 'yiigridSerialColumn'],

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

相关内容

  • 没有找到相关文章

最新更新