Skip to content

Instantly share code, notes, and snippets.

@jamband
Last active September 29, 2015 07:48
Show Gist options
  • Save jamband/1569461 to your computer and use it in GitHub Desktop.
Save jamband/1569461 to your computer and use it in GitHub Desktop.
Yii Framework: Upload a file using a model 2
<?php
class Item extends ActiveRecord
{
...
/**
* @see CActiveRecord::afterValidate()
*/
protected function afterValidate()
{
if (!$this->hasErrors()) {
$this->upload();
}
return parent::afterValidate();
}
/**
* Upload file.
*/
private function upload()
{
$file = CUploadedFile::getInstance($this, 'image');
$this->image = sha1(mt_rand() . microtime()) . '.' . $file->extensionName;
$file->saveAs($this->imagePath . $this->image);
}
/**
* Get images path.
* @return string images path
*/
private function getImagePath()
{
return Yii::getPathOfAlias('webroot.images') . DIRECTORY_SEPARATOR;
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment