Answer the question
In order to leave comments, you need to log in
Yii loading pictures in a model?
I do this
belyakov.su/yii-magazin-3_1-dopilivaem-book
but it turns out to be some kind of crap.
I use this extension www.yiiframework.com/extension/image-column
in model
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name', 'safe'),
array('link', 'unsafe'),
array('link', 'file',
'types'=>'jpg, gif, png, pdf',
'maxSize'=>1024 * 1024 * 5, // 5 MB
'allowEmpty'=>'true',
'tooLarge'=>'Файл весит больше 5 MB. Пожалуйста, загрузите файл меньшего размера.',
),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, name, link', 'safe', 'on'=>'search'),
);
}
<div class="row">
<?php echo $form->labelEx($model,'link'); ?>
<?php echo $form->fileField($model, 'link');
if(!$model->isNewRecord) {
echo CHtml::image(Yii::app()->baseUrl.'/images/pic/' .$model->link, $model->name, array('height'=>100));
}
?>
<?php echo $form->error($model,'link'); ?>
</div>
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'img-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
array(
'class' => 'EImageColumn',
'header' => 'картинка',
'name' => 'link',
'pathPrefix' => Yii::app()->baseUrl . "/images/pic/",
'htmlOptions' => array('style' => 'width: 150px;'),
),
'name',
array(
'class' => 'CButtonColumn',
),
),
));
?>
public function actionCreate()
{
$model = new Img;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Img']))
{
$model->attributes = $_POST['Img'];
$command = Yii::app()->db->createCommand();
$max = Yii::app()->db->createCommand()
->select('max(id) as max')
->from('img')
->queryScalar();
$file_image = CUploadedFile::getInstance($model, 'link');
if (is_object($file_image) && get_class($file_image) === 'CUploadedFile')
$model->link = $file_image;
if ($model->save())
{
if (is_object($file_image))
{
$model->link->saveAs($_SERVER['DOCUMENT_ROOT'].'/techbase/images/pic/' .($max+1).'.'.$file_image->extensionName);
}
$command->update('img', array(
'link' => ($max+1).'.'.$file_image->extensionName,
),'id=:id', array(':id'=>$max+1)
);
$model->link = $max.'.'.$file_image->extensionName;
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
Answer the question
In order to leave comments, you need to log in
Is it really too lazy to google))
Everything is in the manual for uploading files.
One
Two
For creating unique filenames here
Three
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question