Upload Images & Files

Image Upload

In `Config\thumbnail.php`, add the following configuration so the system will pre-generate thumbnail at these respective size.

<?php

$return = array(
	'sample' => array(
		'cover' => array('65x90', '100x138', '100x100', '150x150', '250x345'),
	),
);

In View

<?php $form = $this->beginWidget('ActiveForm', array(
    'id' => 'sample-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation' => false,
    'htmlOptions' => array(
        'class' => 'form-vertical crud-form',
        'role' => 'form',
        'enctype' => 'multipart/form-data',
    )
)); ?>

<div class="form-group <?php echo $model->hasErrors('image_cover') ? 'has-error' : '' ?>">
    <?php echo $form->bsLabelEx2($model, 'image_cover'); ?>
    <div class="col-sm-10">
    <div class="row">
        <div class="col-sm-2 text-left">
            <?php echo Html::activeThumb($model, 'image_cover'); ?>
        </div>
        <div class="col-sm-8">
            <?php echo Html::activeFileField($model, 'imageFile_cover'); ?>
            <span class="help-block"><?php echo Yii::t('app', 'JPG or PNG image only.') ?></span>
            <?php echo $form->bsError($model, 'image_cover'); ?>
        </div>
    </div>
    </div>
</div>


<?php $this->endWidget(); ?>

In Controller

public function actionEdit($id)
{
    $model = $this->loadModel($id);
    if (isset($_POST['Sample'])) {
        $model->attributes = $_POST['Sample'];
        $model->imageFile_cover = UploadedFile::getInstance($model, 'imageFile_cover');

        if ($model->save()) {
            UploadManager::storeImage($model, 'cover', $model->tableName());
        }
    }
}

In Database

This value of 'uploads/sample/cover.1.jpg' will be stored in column image_cover` under table `sample` following naming convention. 1 here is the model id which use as default unique key.

If you like to store the file as a different name, a combination of id-timestamp for example, you can:

UploadManager::storeImage($model, 'cover', $model->tableName(), null, sprintf('%s-%s', $model->id, time()));

Last updated

Was this helpful?