Skip to content

Instantly share code, notes, and snippets.

@jamband
Last active September 28, 2015 13:18
Show Gist options
  • Save jamband/1444205 to your computer and use it in GitHub Desktop.
Save jamband/1444205 to your computer and use it in GitHub Desktop.
Yii Framework: Upload a file using a model.
<div class="form">
<?php echo CHtml::form('', 'post', array('enctype' => 'multipart/form-data')); ?>
<div class="row">
<?php echo CHtml::activeLabel($item, 'title'); ?>
<?php echo CHtml::activeTextField($item, 'title'); ?>
<?php echo CHtml::error($item, 'title'); ?>
</div><!-- /.row -->
<div class="row">
<?php echo CHtml::activeLabel($item, 'image'); ?>
<div class="hint">ファイル形式は <?php echo CHtml::encode(Item::ALLOW_TYPES); ?> のみで、ファイルサイズは 1MB まで</div>
<?php echo CHtml::activeFileField($item, 'image'); ?>
<?php echo CHtml::error($item, 'image'); ?>
</div><!-- /.row -->
<div class="row">
<?php echo CHtml::submitButton($item->isNewRecord ? 'Create' : 'Update'); ?>
</div><!-- /.row -->
<?php echo CHtml::endForm(); ?>
</div><!-- /.form -->
<?php
class Item extends CActiveRecord
{
const ALLOW_TYPES = 'jpg, png, gif';
public $image;
...
/**
* @see CModel::attributeLabels()
*/
public function attributeLabels()
{
return array(
'title' => 'タイトル',
'image' => '画像',
);
}
/**
* @see CModel::rules()
*/
public function rules()
{
$imageRule = array(
'image',
'file',
'safe' => true,
'types' => self::ALLOW_TYPES,
'mimeTypes' => 'image/jpeg, image/pjpeg, image/png, image/x-png, image/gif',
'maxSize' => 1024 * 1024 * 1,
'message' => '{attribute} が選択されていません。',
'wrongType' => '{attribute} の拡張子が正しくありません (' . self::ALLOW_TYPES . ' のみ)',
'wrongMimeType' => '{attribute} のファイル形式が正しくありません。',
'tooLarge' => '{attribute} のファイルサイズが上限を超えています。(1MB まで)',
);
return array(
// title
array('title', 'required'),
array('title', 'length', 'max'=>100),
// file_name
array('file_name', 'safe'),
// image
array_merge($imageRule, array('on'=>'insert')),
array_merge($imageRule, array('allowEmpty'=>true, 'on'=>'update')),
);
}
}
<?php
class ItemController extends Controller
{
public $uploadedFileUrl;
private $uploadedFilePath;
/**
* @see CController::init()
*/
public function init()
{
parent::init();
$this->uploadedFileUrl =
Yii::app()->baseUrl .
'/images/item/';
$this->uploadedFilePath =
Yii::getPathOfAlias('webroot.images.item') .
DIRECTORY_SEPARATOR;
}
...
/**
* Creates a new item.
*/
public function actionCreate()
{
$item = new Item();
if (isset($_POST['Item'])) {
$item->attributes = $_POST['Item'];
if ($item->validate()) {
$image = CUploadedFile::getInstance($item, 'image');
$item->file_name = sha1(mt_rand() . microtime()) . '.' . $image->extensionName;
$image->saveAs($this->uploadedFilePath . $item->file_name);
$item->save(false);
$this->redirect(array('index'));
}
}
$this->render('_form', compact('item'));
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment