Yii2上传的图片不显示

问题描述 投票:0回答:2

因此,我设置了CRUD以将文件上传到服务器的根目录中的“ uploads”文件夹中。 现在,该文件已正确保存在特定的文件夹中,并且数据库条目似乎没问题-但是图像未显示在CRUD的“索引”和“查看”操作中。 对这个有什么想法吗?

创造:

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

        if ($model->load(Yii::$app->request->post())) {

            $model->image = UploadedFile::getInstance($model, 'image');

            if (Yii::$app->ImageUploadComponent->upload($model)) {
                Yii::$app->session->setFlash('success', 'Image uploaded. Category added.');

                return $this->redirect(['view', 'id' => $model->id]);
            } else {
                Yii::$app->session->setFlash('error', 'Proccess could not be successfully completed.');

                return $this->render('create', [
                    'model' => $model
                ]);
            }

        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

ImageUploadComponent文件:

<?php 

namespace app\components;

use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;

class ImageUploadComponent extends Component {

    public function upload($model) {

        if ($model->image) {

            $imageBasePath = dirname(Yii::$app->basePath, 1) . '\uploads\\';
            $imageData = 'img' . $model->image->baseName . '.' . $model->image->extension;

            $time = time();

            $model->image->saveAs($imageBasePath . $time . $imageData);

            $model->image = $imageBasePath . $time . $imageData;

            if ($model->save(false)) {
                return true;
            } else {
                return false;
            }

        }

    }

}

以及视图的索引文件:

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\modules\admin\models\PhotoGalleryCategoriesSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Photo Gallery Categories';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="photo-gallery-categories-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Photo Gallery Categories', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

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

            'name',

            'image' => [
                'attribute' => 'image',
                'value' => 'image',
                'format' => ['image', ['class' => 'col-md-6']]
            ],

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</div>

在此处输入图片说明

编辑:在开发工具中,我可以看到图像的正确来源。 而且,我可以通过在浏览器中复制粘贴地址来访问它。 (第一行是通过其地址从互联网上获取的图像,它们不会保存在本地。)

php image yii upload yii2
2个回答
0
投票

如果图像上传到文件夹中

您可以使用自己的路径在gridview中检查以下代码:

[
                'attribute' => 'image',
                'format' => 'html',
                'value' => function($data) {
                    if (empty($data['image'])) {
                        $img = 'default.jpg';
                    } else {
                        $img = $data['image'];
                    }


                    if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . $img)) {
                        if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . "t-" . $img)) {
                            $path = \Yii::$app->params['path']['webproduct'] . "t-" . $img;
                        } else {
                            $path = \Yii::$app->params['path']['webproduct'] . $img;
                        }
                    } else {
                        if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . "t-default.jpg")) {
                            $path = \Yii::$app->params['path']['webproduct'] . "t-default.jpg";
                        } else {
                            $path = \Yii::$app->params['path']['webproduct'] . "default.jpg";
                        }
                    }

                    return Html::img($path, ['width' => '100px', 'height' => '100px']);
                },
                    ],

在params.php中

\\ Yii的:: $ APP-> PARAMS [ '路径'] [ 'webproduct']:

 'product' => '/web/uploads/product/',
        'webproduct' => '/uploads/product/',

注意:我使用基本模板。


0
投票

我发现了这个异常:在检查图像源时,我发现Yii在图像源之前添加了baseUrl,即使它只显示正确的位。 因此,我手动分配了进入数据库的路径-这样,图像可以正确显示。

这是更改后的上传功能。 为了对整个后端进行测试,我将其作为一个组件,并且可以完美地工作。

    public function upload($model) {

        /**
        * If the $model->image field is not empty, proceed to uploading.
        */
        if ($model->image) {

            /**
            * Assign current time.
            */
            $time = time();

            /**
            * Create the basePath for the image to be uploaded at @root/uploads.
            * Create the image name.
            * Create the database model.
            */
            $imageBasePath = dirname(Yii::$app->basePath, 1) . '\uploads\\';
            $imageData = 'img' . $model->image->baseName . '.' . $model->image->extension;
            $imageDatabaseEntryPath = '../../../uploads/';

            $modelImageDatabaseEntry = $imageDatabaseEntryPath . $time . $imageData;

            $model->image->saveAs($imageBasePath . $time . $imageData);

            $model->image = $modelImageDatabaseEntry;

            /**
            * If the model can be saved into the database, return true; else return false.
            * Further handling will be done in the controller.
            */
            if ($model->save(false)) {
                return true;
            } else {
                return false;
            }

        }

    }

}
© www.soinside.com 2019 - 2024. All rights reserved.