Last active
September 17, 2015 21:43
-
-
Save maximishchenko/a4584c6a4c50291b6f60 to your computer and use it in GitHub Desktop.
Yii upload single file (action "create" and "update")
This file contains 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
<? | |
// There and next: | |
// webroot.images - path to images forlder (such as Yii::app()->baseurl."/images/") | |
// if using another forder name (for example: /upload/) - Yii::getPathOfAlias('webroot.upload') | |
// file_field_name - db field that contains name of uploaded file | |
// DIRECTORY_SEPARATOR - separator, such as "/" or included folders | |
// PATH_TO_IMAGE_FOLDER - full path to folder with images | |
// Previously added CImageHandler and Fancybox extensions | |
// CImageHandler: | |
// Copied file ImageHandler to Components folder | |
// In config/main.php added | |
// 'components'=>array( | |
// ... | |
// 'ih'=>array( | |
// 'class'=>'CImageHandler', | |
// ), | |
// ... | |
// ) | |
// Also can use where needed | |
// $ih = new CImageHandler(); | |
// Fancybox: | |
// Extension copied to Extensions folder | |
// Model code | |
public function rules() | |
{ | |
return array( | |
// ... | |
// File types sets based on images upload (change if need) | |
// Maximum filesize set in bytes, current based on php.ini values | |
array('<file_field_name>', 'file', 'types'=>'jpg, jpeg, gif, png', 'maxSize'=>2097152, 'tooLarge'=>'Размер загружаемого файла не должен превышать 2MB', 'allowEmpty'=>true,'safe' => false), | |
// ... | |
); | |
} | |
// Delete file when delete record from database | |
protected function beforeDelete() | |
{ | |
if (parent::beforeDelete()) { | |
if ($this-><file_field_name>) | |
@unlink(Yii::getPathOfAlias('webroot.images') . "DIRECTORY_SEPARATOR" . $this-><file_field_name>); | |
return true; | |
} return false; | |
} | |
// Controller code | |
public function actionCreate() | |
{ | |
// <Model> - abstract name of model (need to change) | |
$model=new <ModelName>; | |
// Ajax validation | |
$this->performAjaxValidation($model); | |
if(isset($_POST['<ModelName>'])) | |
{ | |
// Current date (format example: month-day-year-hour-minute-second) | |
$date = date('m-d-Y-h-i-s', time()); | |
// <file_field_name> - db field that contains name of uploaded file | |
$name = $_FILES['<ModelName>']['name']['<file_field_name>']; | |
// filename without extension | |
$filename = pathinfo($name, PATHINFO_FILENAME); | |
// only current file extension without filename | |
$ext = pathinfo($name, PATHINFO_EXTENSION); | |
// summary previous variables for new filename | |
$imgName = $date.'-'.$filename.'.'.$ext; | |
// Set model attributes | |
$model->attributes=$_POST['<ModelName>']; | |
$model-><file_field_name> = CUploadedFile::getInstance($model,'<file_field_name>'); | |
if($model->save() && !empty($model-><file_field_name>)){ | |
// Path to save files | |
$imgSrc = Yii::getPathOfAlias('webroot.images').'DIRECTORY_SEPARATOR'.$imgName; | |
// Save file | |
$model-><file_field_name>->saveAs($imgSrc); | |
// Load CImageHandler Component | |
Yii::app()->ih | |
// Load original image | |
->load($imgSrc) | |
// resize to 640x480 with proportional | |
->resize(640, 480, true) | |
// save and move original image file | |
->save($_SERVER['DOCUMENT_ROOT'] . 'PATH_TO_IMAGE_FOLDER'.$imgName); | |
// Write filename into database | |
$model-><file_field_name> = $imgName; | |
// Save model | |
$model->save(); | |
// Set success flash message | |
Yii::app()->user->setFlash('success','Подразделение добавлено!'); | |
$this->redirect(array('view','id'=>$model->id)); | |
} | |
elseif($model->save() && empty($model-><file_field_name>)){ | |
// Set success flash message | |
Yii::app()->user->setFlash('success','Подразделение добавлено!'); | |
$this->redirect(array('view','id'=>$model->id)); | |
} | |
} | |
$this->render('create',array( | |
'model'=>$model, | |
)); | |
} | |
public function actionUpdate($id) | |
{ | |
// Load model | |
$model=$this->loadModel($id); | |
// Save current field value to variable | |
$oldImgName = $model-><file_field_name>; | |
// Ajax validation | |
$this->performAjaxValidation($model); | |
if(isset($_POST['<ModelName>'])) | |
{ | |
// Current date (format example: month-day-year-hour-minute-second) | |
$date = date('m-d-Y-h-i-s', time()); | |
// <file_field_name> - db field that contains name of uploaded file | |
$name = $_FILES['<ModelName>']['name']['<file_field_name>']; | |
// filename without extension | |
$filename = pathinfo($name, PATHINFO_FILENAME); | |
// only current file extension without filename | |
$ext = pathinfo($name, PATHINFO_EXTENSION); | |
// summary previous variables for new filename | |
$imgName = $date.'-'.$filename.'.'.$ext; | |
// Set model attributes | |
$model->attributes=$_POST['<ModelName>']; | |
$model-><file_field_name> = CUploadedFile::getInstance($model,'<file_field_name>'); | |
if($model->save() && !empty($model-><file_field_name>)){ | |
// Delete previous file | |
@unlink(Yii::getPathOfAlias('webroot.images').'DIRECTORY_SEPARATOR'.$oldImgName); | |
// Path to save files | |
$imgSrc = Yii::getPathOfAlias('webroot.images').'DIRECTORY_SEPARATOR'.$imgName; | |
// Save file | |
$model-><file_field_name>->saveAs($imgSrc); | |
// Load CImageHandler Component | |
Yii::app()->ih | |
// Load original image | |
->load($imgSrc) | |
// resize to 640x480 with proportional | |
->resize(640, 480, true) | |
// save and move original image file | |
->save($_SERVER['DOCUMENT_ROOT'] . 'PATH_TO_IMAGE_FOLDER'.$imgName); | |
// Write filename into database | |
$model-><file_field_name> = $imgName; | |
// Save model | |
$model->save(); | |
// Set success flash message | |
Yii::app()->user->setFlash('success','Информация о подразделении изменена!'); | |
$this->redirect(array('view','id'=>$model->id)); | |
} | |
elseif($model->save() && empty($model-><file_field_name>)){ | |
// Set <file_field_name> previous value of filename | |
$model-><file_field_name> = $oldImgName; | |
// Save model | |
$model->save(); | |
// Set success flash message | |
Yii::app()->user->setFlash('success','Информация о подразделении изменена!'); | |
$this->redirect(array('view','id'=>$model->id)); | |
} | |
} | |
$this->render('update',array( | |
'model'=>$model, | |
)); | |
} | |
// Show current image file on update | |
// In _form.php: | |
echo $form->labelEx($model, '<file_field_name>'); | |
echo $form->fileField($model, '<file_field_name>'); | |
if($model->isNewRecord!='1' && !empty($model-><file_field_name>)){ | |
$this->widget('application.extensions.fancybox.EFancyBox', array( | |
'target'=>'.fancy-inline', | |
'config'=>array( | |
'closeBtn' => false, | |
'titlePosition'=>'outside', | |
'helpers' => array ( 'title' => array ('type' => 'inside' ), 'buttons' => array() ) | |
) | |
) | |
); | |
?> | |
<li style="list-style: none;"> | |
<a href="#" class="fancy-inline" rel="tooltip" data-title="<data_title>"> | |
<?php | |
$prev = CHtml::image(Yii::app()->request->baseUrl . 'PATH_TO_IMAGE_FOLDER'.$model-><file_field_name>, '', array('style' => 'width:100px; height: 100px; border-radius: 15px; box-shadow: 0 1px 4px rgba(0, 0, 0, .3), -23px 0 20px -23px rgba(0, 0, 0, .8), 23px 0 20px -23px rgba(0, 0, 0, .8), 0 0 40px rgba(0, 0, 0, .1) inset;')); | |
echo CHtml::link($prev, Yii::app()->request->baseUrl.'PATH_TO_IMAGE_FOLDER'.$model-><file_field_name>, array('class' => 'fancy-inline', 'rel'=>'group')); | |
?> | |
</a> | |
</li> | |
<?php | |
} | |
echo $form->error($model, '<file_field_name>'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment