Last active
September 29, 2015 07:48
-
-
Save jamband/1569461 to your computer and use it in GitHub Desktop.
Yii Framework: Upload a file using a model 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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