所以我設置了一個CRUD上傳文件到服務器的根目錄,名爲'uploads'。 現在,該文件已正確保存在特定文件夾中,並且數據庫條目看起來沒問題 - 但圖像不顯示在CRUD的「索引」和「視圖」操作中。對此有任何想法?Yii2上傳的圖像不顯示
創建:
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>
編輯:在開發ŧ ools,我可以看到圖像的正確來源。更重要的是,我可以通過在瀏覽器中複製地址來訪問它。 (第一行是從互聯網上通過自己的地址拍攝的圖像,他們都不會在本地保存。)
我有類似的問題,但認爲這是一些特定的網格視圖中,在文檔是一無所知,但你可以做的是安裝卡爾蒂克和使用GridView和DatePicker的它會解決很多未來的問題。 – Alexei
將文件上傳到文件夾中? –