/** * @param \CActiveRecord $model * @param string $attribute имя поля, содержащего CUploadedFile. В последствии этому полю будет присвоено имя файла изображения. * @param \CUploadedFile $image * @param array $sizes * * @throws \CException * * @return bool */ public function save(\CActiveRecord $model, $attribute = 'image', \CUploadedFile $image, $sizes = []) { $folderModel = $this->extractPath($model, $attribute, true); if (!file_exists($folderModel)) { mkdir($folderModel); } $imageExtension = isset($this->mimeToExtension[$image->getType()]) ? $this->mimeToExtension[$image->getType()] : 'jpg'; $imageId = $this->getRandomHash($model, $attribute); $imagePathTemp = \Yii::getPathOfAlias('temp') . '/' . $imageId . '.' . $imageExtension; if ($image->saveAs($imagePathTemp)) { foreach ($sizes as $sizeName => $size) { $folderModelAttribute = $this->extractPath($model, $attribute); if (!file_exists($folderModelAttribute)) { mkdir($folderModelAttribute); } $quality = array_key_exists('quality', $size) ? intval($size['quality']) : self::DEFAULT_QUALITY; if ($quality <= 0 or $quality > 100) { $quality = self::DEFAULT_QUALITY; } $pathImageSize = $folderModelAttribute . '/' . $imageId . '_' . $sizeName . '.' . $imageExtension; if (array_key_exists('enabled', $size) and $size['enabled'] == false) { if (array_key_exists('resave', $size) and $size['resave'] == false) { rename($imagePathTemp, $pathImageSize); } else { $this->processor->open($imagePathTemp)->save($pathImageSize, ['quality' => $quality]); } } else { $this->processor->open($imagePathTemp)->thumbnail(new Box($size['width'], $size['height']), (!isset($size['inset']) or $size['inset']) ? ImageInterface::THUMBNAIL_INSET : ImageInterface::THUMBNAIL_OUTBOUND)->save($pathImageSize, ['quality' => $quality]); } } } else { throw new \CException('can not save image'); } return [self::KEY_ID => $imageId, self::KEY_EXT => $imageExtension]; }
/** * Save file meta data to persistent storage and return id. * * @param \CUploadedFile $uploadedFile uploaded file. * * @return integer meta data identifier in persistent storage. */ public function saveMetaDataForUploadedFile(\CUploadedFile $uploadedFile) { $ext = \mb_strtolower($uploadedFile->getExtensionName(), 'UTF-8'); $realName = pathinfo($uploadedFile->getName(), PATHINFO_FILENAME); FPM::m()->getDb()->createCommand()->insert(FPM::m()->tableName, array('extension' => $ext, 'real_name' => $realName)); return FPM::m()->getDb()->getLastInsertID(); }
public function run() { $this->prepare(); if ($file = new CUploadedFile($this->md5($_FILES['file']['name']), $_FILES['file']['tmp_name'], $_FILES['file']['type'], $_FILES['file']['size'], $_FILES['file']['error'])) { if ($file->saveAs($this->basePath . $file->getName())) { $this->append($file->getName()); } } }
public function changeLogo(CUploadedFile $uploadedFile) { $basePath = Yii::app()->getModule('cabinet')->getUploadPath(); //создаем каталог для аватарок, если не существует if (!is_dir($basePath) && !@mkdir($basePath, 0755, true)) { throw new CException(Yii::t('default', 'It is not possible to create directory for logos!')); } $filename = $this->id . '_' . time() . '.' . $uploadedFile->extensionName; // обновить файл //$this->removeOldLogo(); if (!$uploadedFile->saveAs($basePath . $filename)) { throw new CException(Yii::t('default', 'It is not possible to save logos!')); } // получить запись лого $photo = $this->with('photo')->find('photo.id=:id', [':id' => $this->logo_id]); $webroot = Yii::getpathOfAlias('webroot'); $trimPath = str_replace($webroot, '', $basePath); $logoFileOld = null; $File = new File(); $File->model = 'Company'; $File->type = 'image'; $File->size = filesize($basePath . $filename); $File->name = $filename; $File->path = $trimPath . $filename; $File->record_id = 0; if (!is_null($photo['photo'])) { $File->id = $photo['photo']['id']; $File->isNewRecord = false; $logoFileOld = $photo['photo']['path']; } if ($File->save()) { if (0 != strcmp($logoFileOld, $File->path)) { @unlink($webroot . $logoFileOld); } } else { yii::log("changeLogo save FAILED id=[" . $File->id . "]", "info"); } if ($this->logo_id != $File->id) { // поменять logo_id $this->logo_id = $File->id; if ($this->validate(['logo_id'])) { if (true === $this->update(['logo_id'])) { } else { Yii::log("changeLogo update logo_id FAILED", 'info'); } } else { Yii::log("changeLogo validate logo_id FAILED", 'info'); } } //$this->logo = $filename; return true; }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. */ public function actionEdit() { $model = $this->loadUser(); $profile = $model->profile; // ajax validator if (isset($_POST['ajax']) && $_POST['ajax'] === 'profile-form') { echo UActiveForm::validate(array($model, $profile)); Yii::app()->end(); } if (isset($_POST['User'])) { $model->attributes = $_POST['User']; $model->image = CUploadedFile::getInstance($model, 'image'); $profile->attributes = $_POST['Profile']; if ($model->validate() && $profile->validate()) { $model->save(); $profile->save(); Yii::app()->user->updateSession(); Yii::app()->user->setFlash('profileMessage', Yii::t('main', "Data saved successfully!")); $this->redirect(array('/user/profile')); } else { $profile->validate(); } } $this->render('edit', array('model' => $model, 'profile' => $profile)); }
public function actionIndex($is_product = 1) { if (!empty($_POST)) { $is_new_product = $is_product; $images = CUploadedFile::getInstancesByName('images'); if (isset($images) && count($images) > 0) { // go through each uploaded image foreach ($images as $image => $pic) { $model = new Slides(); $imageType = explode('.', $pic->name); $imageType = $imageType[count($imageType) - 1]; $imageName = md5(uniqid()) . '.' . $imageType; if ($pic->saveAs(Yii::getPathOfAlias('webroot') . '/upload/images/' . $imageName)) { $model->image = $imageName; $model->name = $pic->name; $model->is_product = $is_new_product; $model->save(); Yii::app()->user->setFlash('success', translate('Thêm thành công.')); } // handle the errors here, if you want } } PIUrl::createUrl('/admin/slides/index', array('is_product' => $is_product)); } $criteria = new CDbCriteria(); $criteria->addCondition("is_product= {$is_product}"); $criteria->order = 'id DESC'; $count = Slides::model()->count($criteria); $pages = new CPagination($count); // results per page $pages->pageSize = 6; $pages->applyLimit($criteria); $model = Slides::model()->findAll($criteria); $this->render('index', compact('model', 'pages')); }
public function afterValidate($event) { $this->prepareDataDirectory(); $file = CUploadedFile::getInstanceByName($this->uploadInstance); if ($file instanceof CUploadedFile && $file->getError() == UPLOAD_ERR_OK && !$this->Owner->hasErrors()) { $uniqueFilename = P3StringHelper::generateUniqueFilename($file->getName()); $fullFilePath = $this->_fullDataPath . DIRECTORY_SEPARATOR . $uniqueFilename; $relativeFilePath = $this->_relativeDataPath . DIRECTORY_SEPARATOR . $uniqueFilename; if ($file->saveAs($fullFilePath)) { #echo $fullFilePath;exit; if (!$this->Owner->isNewRecord) { $this->deleteFile($this->Owner->path); } if (!$this->Owner->title) { $this->Owner->title = P3StringHelper::cleanName($file->name, 32); } $this->Owner->path = $relativeFilePath; $this->Owner->mimeType = $file->type; $this->Owner->size = $file->size; $this->Owner->originalName = $file->name; $this->Owner->md5 = md5_file($fullFilePath); } else { $this->Owner->addError('filePath', 'File uploaded failed!'); } } else { if ($this->Owner->isNewRecord) { #$this->Owner->addError('filePath', 'No file uploaded!'); Yii::trace('No file uploaded!'); } } }
/** * Upload file and process it for mapping. */ public function actionUpload() { // Get import post $import = craft()->request->getRequiredPost('import'); // Get file $file = \CUploadedFile::getInstanceByName('file'); // Is file valid? if (!is_null($file)) { // Determine folder $folder = craft()->path->getStoragePath() . 'import/'; // Ensure folder exists IOHelper::ensureFolderExists($folder); // Get filepath - save in storage folder $path = $folder . $file->getName(); // Save file to Craft's temp folder for later use $file->saveAs($path); // Put vars in model $model = new ImportModel(); $model->filetype = $file->getType(); // Validate filetype if ($model->validate()) { // Get columns $columns = craft()->import->columns($path); // Send variables to template and display $this->renderTemplate('import/_map', array('import' => $import, 'file' => $path, 'columns' => $columns)); } else { // Not validated, show error craft()->userSession->setError(Craft::t('This filetype is not valid') . ': ' . $model->filetype); } } else { // No file uploaded craft()->userSession->setError(Craft::t('Please upload a file.')); } }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Scodobjventascaract'])) { $model->attributes = $_POST['Scodobjventascaract']; // Verificar si existe un archivo que actualizar en la creacion if (isset($_FILES) && $_FILES['Scodobjventascaract']['error']['imagen'] == 0) { // Obtenemos la instancia del documento $fDocumento = CUploadedFile::getInstance($model, 'imagen'); $sPathDocumento = $sPathFile . '/' . $model->id_cod_obj_venta . '/'; if (!file_exists($sPathDocumento)) { mkdir($sPathDocumento, 0777, true); } $fDocumento->saveAs($sPathDocumento . $fDocumento->getName()); $model->imagen = $fDocumento->getName(); // $this->refresh(); } if ($model->save()) { $this->redirect(array('scodobjventas/' . $model->id_cod_obj_venta)); } } $this->render('update', array('model' => $model)); }
public function actionUpdate() { $model = $this->loadModel($id); if (isset($_POST['Avatars'])) { $model->attributes = $_POST['Avatars']; $model->icon = CUploadedFile::getInstance($model, 'icon'); if ($model->icon) { $sourcePath = pathinfo($model->icon->getName()); $fileName = date('m-d') . Yii::app()->user->name . '.' . $sourcePath['extension']; $model->image = $fileName; } if ($model->save()) { //Если отмечен чекбокс «удалить файл» if ($model->del_img) { if (file_exists($_SERVER['DOCUMENT_ROOT'] . Yii::app()->urlManager->baseUrl . '/images/' . $model->image)) { //удаляем файл unlink('./images/' . $model->image); $model->image = ''; } } //Если поле загрузки файла не было пустым, то if ($model->icon) { $file = './images/' . $fileName; $model->icon->saveAs($file); $image = Yii::app()->image->load($file); $image->resize(100, 100); $image->save(); } $this->redirect(array('update', 'id' => $model->id)); } } $this->render('update', array('model' => $model)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new MCompany(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['MCompany'])) { $model->attributes = $_POST['MCompany']; $brandImage = CUploadedFile::getInstance($model, 'image_id'); if ($brandImage instanceof CUploadedFile) { $image = new MImage(); $path_parts = pathinfo($brandImage->getName()); $file_name = time() . "." . $path_parts['extension']; $path = Yii::app()->storagePath . "brand" . DIRECTORY_SEPARATOR . $file_name; $brandImage->saveAs($path); $image->created = time(); $image->path = "/storage/brand/" . $file_name; $image->created_by = Yii::app()->user->id; $image->save(false); } $model->image_id = $image->id; $model->created = time(); $model->created_by = Yii::app()->user->id; if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('create', array('model' => $model)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Photo(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Photo'])) { $model->attributes = $_POST['Photo']; $picture_name = ''; $picture_file = CUploadedFile::getInstance($model, 'file'); $model->file = $picture_file; if ($picture_file) { $picture_name = $picture_file->name; if (!is_dir(Yii::getPathOfAlias('webroot') . '/themes/gallery-images/')) { mkdir(Yii::getPathOfAlias('webroot') . '/themes/gallery-images/'); } if (!is_dir(Yii::getPathOfAlias('webroot') . '/themes/gallery-images/')) { mkdir(Yii::getPathOfAlias('webroot') . '/themes/gallery-images/'); $picture_file->SaveAs(Yii::getPathOfAlias('webroot') . '/themes/gallery-images' . $picture_file->getName()); } else { $picture_file->SaveAs(Yii::getPathOfAlias('webroot') . '/themes/gallery-images' . $picture_file->getName()); } } if ($model->save()) { $this->redirect(array('view', 'id' => $model->photo_id)); } } $this->render('create', array('model' => $model)); }
public function run() { $file = CUploadedFile::getInstanceByName('file'); $path = $this->getUniquePath($this->filesDir(), $file->extensionName); $file->saveAs($path); echo CHtml::link($file->name, "http://" . $_SERVER["HTTP_HOST"] . '/' . $path); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Partner'])) { $model->attributes = $_POST['Partner']; $model->fileLogo = CUploadedFile::getInstance($model, 'fileLogo'); if ($model->fileLogo) { if ($model->validate(array('fileLogo'))) { $fileName = $this->getAndSaveUploadedFile($model); if ($fileName) { if ($model->logo_path && file_exists($model->logo_path)) { unlink($model->logo_path); } $model->logo_path = $fileName; } } } if ($model->save()) { $this->redirect(array('admin')); } } $this->render('update', array('model' => $model)); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Slider'])) { if (file_exists(Yii::app()->basePath . self::URLUPLOAD . $model->file_name)) { unlink(Yii::app()->basePath . self::URLUPLOAD . $model->file_name); } $model->attributes = $_POST['Slider']; $uploadedFile = CUploadedFile::getInstance($model, 'file_name'); $rnd = rand(0, 999999); $wkt = date('m-d-Y-h-i-s', time()); $fileName = "{$wkt}_{$rnd}_{$uploadedFile}"; $model->file_name = $fileName; $model->last_update = new CDbExpression('NOW()'); if ($model->save()) { if ($uploadedFile !== null) { $uploadedFile->saveAs(Yii::app()->basePath . self::URLUPLOAD . $model->file_name); } $this->redirect(array('view', 'id' => $model->id)); } } $this->render('update', array('model' => $model)); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); $menu = $model->attributes; if (isset($_POST['FrontMenu'])) { $model->attributes = $_POST['FrontMenu']; foreach ($this->uploadArr as $column) { $file = CUploadedFile::getInstance($model, $column); //获取表单名为filename的上传信息 if ($file) { $model->{$column} = $this->uploadIcon($file); if ($menu[$column]) { $ftp = new Ftp(); $res = $ftp->delete_file('common/frontmenu/' . $menu[$column]); $ftp->close(); } } else { unset($model->{$column}); } } if (!$model->ParentID) { $model->ParentID = 0; } if ($model->save()) { $this->freshMenuCache(); $this->redirect(array('admin')); } } $this->render('update', array('model' => $model)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Pic(); if (isset($_POST['Pic'])) { $image = CUploadedFile::getInstances($model, 'big_pic'); $is_fail = true; foreach ($image as $img) { $model->created_time = date("Y-m-d H:i:s"); $microtime = microtime(true); $model->big_pic = './images/pic/' . $microtime . '.' . $img->extensionName; $mini_path = $this->create_mini_pic($img->tempName, $microtime); $model->mini_pic = $mini_path; if ($model->save()) { $is_fail = false; $img->saveAs($model->big_pic); } else { print_r($model->getErrors()); } } if (!$is_fail) { $this->redirect(array('index')); } } $this->render('create', array('model' => $model)); }
public function actionUpload() { $cs = Yii::app()->getClientScript(); $cs->registerCoreScript('jquery'); $model = new Image(); if (isset($_FILES['Image'])) { $model->image = CUploadedFile::getInstance($model, 'image'); if ($model->validate()) { $name = $model->image->name; if (file_exists(Yii::app()->params['imageHomeAbs'] . $name)) { // already there $v = 2; preg_match('/(\\w+)\\.(\\w+)/', $name, $match); do { $name = $match[1] . '(' . $v++ . ').' . $match[2]; } while (file_exists(Yii::app()->params['imageHomeAbs'] . $name)); } if ($model->validate()) { $model->image->saveAs(Yii::app()->params['imageHomeAbs'] . $name); } } } // directory search $current = Yii::app()->params['imageHomeAbs']; $filelist = array(); $d = dir($current); while ($tmp = $d->read()) { if ($tmp != '.' && $tmp != '..' && $tmp != '.svn') { array_push($filelist, $tmp); } } asort($filelist, SORT_STRING); $this->render('gallery', array('model' => $model, 'filelist' => $filelist, 'current' => $current, 'cs' => $cs)); }
public function beforeSave() { parent::beforeSave(); $picture = CUploadedFile::getInstance($this, 'image'); if ($picture) { $imagename = $picture->getTempName(); $image = Yii::app()->image->load($imagename); if ($image) { if ($this->avatar) { unlink($_SERVER['DOCUMENT_ROOT'] . $this->avatar_folder . '/' . $this->avatar); } if ($image->width >= $image->height) { $image->resize(20000, 93)->rotate(0)->quality(90)->sharpen(20); } else { $image->resize(93, 20000)->rotate(0)->quality(90)->sharpen(20); } $image->crop(93, 93); $file_name = rand() . '.' . $picture->extensionName; $savename = $_SERVER['DOCUMENT_ROOT'] . $this->avatar_folder . '/' . $file_name; $image->save($savename); $this->avatar = $file_name; } } return true; }
public function actionUpdate($id = null) { $model = Documents::model()->findByPk($id); $flag = 0; if (!empty($_POST['Documents'])) { $filename_old = $model->attributes['filename']; if (!empty(CUploadedFile::getInstance($model, 'filename')->name)) { $model->attributes = $_POST['Documents']; $model->filename = CUploadedFile::getInstance($model, 'filename'); $filename = $model->filename; $document = explode('.', $model->filename->name); $filenameType = $document[count($document) - 1]; $filenameName = md5(uniqid()) . '.' . $filenameType; $model->type = end($document); $model->size = $model->filename->size; $model->md5name = $filenameName; $model->filename = $document[count($document) - 2] . "." . $model->type; $filenames_path = Yii::getPathOfAlias('webroot') . '/upload/documents/' . $filenameName; $flag = 1; } else { $model->attributes = $_POST['Documents']; $model->filename = $filename_old; } $model->updated = time(); if ($model->save()) { Yii::app()->user->setFlash('success', translate('Cập nhật thành công.')); if ($flag == 1) { $filename->saveAs($filenames_path); } $this->redirect(PIUrl::createUrl('/admin/Documents/')); } } $dataCategories = categoriesDocuments::model()->getCategoriesDocument(); $this->render('update', array('model' => $model, 'dataCategory' => $dataCategories)); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. */ public function actionUpdate() { $model = $this->loadModel(); if (isset($_POST['Post'])) { $model->attributes = $_POST['Post']; $prefix = rand(0, 99); // generate random number between 0-99 $uploadedFile = CUploadedFile::getInstance($model, 'icon'); $sourcePath = Yii::app()->basePath . '/../images/uploads/'; $fileName = "{$prefix}-{$uploadedFile}"; $model->image = $fileName; if ($model->save()) { /* * uncomment this field for the activate checkbox for remove image * */ /*if($model->del_img) { if(file_exists(Yii::getPathOfAlias('webroot').'/images/uploads/'.$model->image)) { unlink(Yii::getPathOfAlias('webroot').'/images/uploads/'.$model->image); } }*/ $uploadedFile->saveAs($sourcePath . $fileName); // image will upload to rootDirectory/images/uploads/ $model->icon = $fileName; } $this->redirect(array('view', 'id' => $model->id)); } $this->render('update', array('model' => $model)); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['FriendLink'])) { $model->attributes = $_POST['FriendLink']; $FriendLink = FriendLink::model()->findByPk($id); $img = $_FILES['FriendLink']['name']['image']; if ($img !== '') { $img = CUploadedFile::getInstance($model, 'image'); $extensionName = explode('.', $img->getName()); $extensionName = $extensionName[count($extensionName) - 1]; $dir = dirname(Yii::app()->basePath) . '/upload/link/'; $img_src = $dir . md5(time()) . '.' . $extensionName; $img1 = md5(time()) . '.' . $extensionName; $model->image = $img1; } else { $model->image = $FriendLink->image; } //$model->cate_id = $_POST['Caigou']['cate_id']; if ($model->save()) { if ($img !== '') { @unlink(dirname(Yii::app()->basePath) . '/upload/link/' . $FriendLink->image); $img->saveAs($img_src); } $this->redirect(array('/cms/friendLink/admin')); } } $this->render('update', array('model' => $model)); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'update' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = new BanersElements(); $root = BanersRubrics::getRoot(new BanersRubrics()); $catalog = $root->descendants()->findAll($root->id); $model = $this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); // set attributes from get if (isset($_GET['BanersElements'])) { $model->attributes = $_GET['BanersElements']; } if (isset($_POST['BanersElements'])) { $model->attributes = $_POST['BanersElements']; $model->imagefile = CUploadedFile::getInstance($model, 'imagefile'); if (isset($model->imagefile)) { $ext = pathinfo($model->imagefile); $model->image = $ext['extension']; } if ($model->save()) { if (isset($model->imagefile) && ($modelSettings = SiteModuleSettings::model()->find('site_module_id = 15'))) { //Загружаем картинку $filename = $model->id . '.' . $model->image; $filepatch = '/../uploads/filestorage/baners/elements/'; $model->imagefile->saveAs(YiiBase::getPathOfAlias('webroot') . $filepatch . $filename); //Обработка изображения SiteModuleSettings::model()->chgImgModel($modelSettings, 'GD', 2, $model->id); } $url = isset($_POST['go_to_list']) ? $this->listUrl('index') : $this->itemUrl('update', $model->id); $this->redirect($url); } } $this->render('update', array('model' => $model, 'root' => $root, 'catalog' => $catalog)); }
public function actionUpdate($id) { $model = $this->loadModel($id); if (isset($_POST["{$this->modelName}"])) { $model->attributes = $_POST["{$this->modelName}"]; $newImage = isset($_FILES['Themes']) && $_FILES['Themes']['name']['upload_img']; if ($newImage) { // delete old image $model->delImage(); $model->scenario = 'upload'; } if ($model->validate()) { if ($newImage) { $model->upload = CUploadedFile::getInstance($model, 'upload_img'); $model->bg_image = md5(uniqid()) . '.' . $model->upload->extensionName; } if ($model->save()) { if ($newImage) { $model->upload->saveAs(Yii::getPathOfAlias($model->path) . '/' . $model->bg_image); Yii::app()->user->setFlash('success', tt('Image successfully added', 'themes')); } else { Yii::app()->user->setFlash('success', tc('Success')); } $this->refresh(); } } } $this->render('update', array('model' => $model)); }
public function actionUpdate($id) { $model = $this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); $oldFileName = $model->picture; if (isset($_POST['News'])) { $model->attributes = $_POST['News']; $uploader = CUploadedFile::getInstance($model, 'picture'); if ($uploader) { $sourcePath = pathinfo($uploader->getName()); $md5_name = md5(date('H:i:s')); $fileName = $md5_name . '.' . $sourcePath['extension']; //generate new filename $model->picture = $fileName; } if ($model->save()) { if ($uploader) { @unlink(ROOT_DIR . '/images/news/' . $oldFileName); @unlink(ROOT_DIR . '/images/news/thumb/' . $oldFileName); $uploader->saveAs(ROOT_DIR . '/images/news/' . $fileName); // $this->saveThumb($md5_name, $sourcePath['extension']); } $this->redirect($this->createUrl('index')); } } $this->render('update', array('model' => $model)); }
public static function saveOther(Apartment $ad) { if (ApartmentVideo::saveVideo($ad)) { $ad->panoramaFile = CUploadedFile::getInstance($ad, 'panoramaFile'); $ad->scenario = 'panorama'; if (!$ad->validate()) { return false; } } $city = ""; if (issetModule('location')) { $city .= $ad->locCountry ? $ad->locCountry->getStrByLang('name') : ""; $city .= $city && $ad->locCity ? ", " : ""; $city .= $ad->locCity ? $ad->locCity->getStrByLang('name') : ""; } else { $city = $ad->city ? $ad->city->getStrByLang('name') : ""; } // data if ($ad->address && $city && (param('useGoogleMap', 1) || param('useYandexMap', 1) || param('useOSMMap', 1))) { if (!$ad->lat && !$ad->lng) { # уже есть $coords = Geocoding::getCoordsByAddress($ad->address, $city); if (isset($coords['lat']) && isset($coords['lng'])) { $ad->lat = $coords['lat']; $ad->lng = $coords['lng']; } } } return true; }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['KqxsNam'])) { $oldimage = $model->image; $model->attributes = $_POST['KqxsNam']; $model->image = CUploadedFile::getInstance($model, 'image'); if ($model->image != NULL) { $folder = 'upload/' . date('Ymd'); if (!file_exists($folder)) { mkdir($folder); } $model->image->saveAs($folder . '/' . $model->image); $model->image = $folder . '/' . $model->image; } else { $model->image = $oldimage; } if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('update', array('model' => $model)); }
/** * edit a particular model. */ public function actionEdit() { $this->layout = '//layouts/notitle_main'; $infoType = $this->getInfoType(); $basicModelName = ucfirst(strtolower($infoType)) . 'InfoView'; $isPageDirty = 0; $actionType = 'view'; if (!empty($_GET['action'])) { $actionType = $_GET['action']; } list($productId, $model, $customInfo, $customFieldArr) = InfoService::initInfoPage($infoType, $this, $actionType, Yii::app()->request); if (!Info::isProductAccessable($productId)) { throw new CHttpException(400, Yii::t('Common', 'Required URL not found or permission denied.')); } if (isset($_POST[$basicModelName])) { if ('' == $_POST['templateTitle'] && empty($_POST['isPageDirty']) && !empty($model->id) && $this->isEditAction($actionType)) { $this->redirect(array('edit', 'type' => $infoType, 'id' => $model->id)); } else { $attachmentFile = CUploadedFile::getInstancesByName('attachment_file'); list($model, $customFieldArr) = InfoService::saveInfoPage($infoType, $model, $customInfo, $attachmentFile, $this, $actionType, Yii::app()->request); $isPageDirty = 1; } } $buttonList = InfoService::getButtonList($infoType, $actionType, $model); $this->render('edit', array('infoType' => $infoType, 'isPageDirty' => $isPageDirty, 'actionType' => $actionType, 'model' => $model, 'buttonList' => $buttonList, 'customfield' => $customFieldArr)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Photo(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Photo'])) { $model->attributes = $_POST['Photo']; if (isset($_FILES['images']['name'][0]) && $_FILES['images']['name'][0] !== '') { $model->name = 'new'; } if ($model->validate()) { $images = CUploadedFile::getInstancesByName('images'); foreach ($images as $image) { $imageModel = new Photo(); $name = uniqid() . $image->name; $image->saveAs(Yii::getPathOfAlias('webroot.uploads.images') . DIRECTORY_SEPARATOR . $name); copy(Yii::getPathOfAlias('webroot.uploads.images') . DIRECTORY_SEPARATOR . $name, Yii::getPathOfAlias('webroot.uploads.images') . DIRECTORY_SEPARATOR . 'thumbs' . DIRECTORY_SEPARATOR . $name); $thumb = Yii::app()->image->load(Yii::getPathOfAlias('webroot.uploads.images') . DIRECTORY_SEPARATOR . 'thumbs' . DIRECTORY_SEPARATOR . $name); $thumb->resize(300, 300); $thumb->save(); $imageModel->name = $name; $imageModel->category_id = $_POST['Photo']['category_id']; $imageModel->save(); } Yii::app()->user->setFlash('success', Yii::t('main', 'Данные успешно сохранены!')); $this->refresh(); } else { Yii::app()->user->setFlash('error', Yii::t('main', 'Ошибка!')); } } $this->render('create', array('model' => $model)); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Links'])) { $oldlogo = $model->logo; $model->attributes = $_POST['Links']; $model->update_uid = Yii::app()->user->id; $model->update_time = date('Y-m-d H:i:s'); $image = CUploadedFile::getInstance($model, 'logo'); if ($image) { $savename = Yii::app()->params['uploadPath'] . time() . mt_rand(1, 999) . '.' . $image->extensionName; $model->logo = '/' . $savename; if ($model->validate()) { $image->saveAs($savename); } if (file_exists($oldlogo)) { unlink($oldlogo); } } else { $model->logo = $oldlogo; } if ($model->save()) { //$this->redirect(array('view','id'=>$model->id)); Yii::app()->user->setFlash('success', '信息提交成功!'); } else { Yii::app()->user->setFlash('success', '信息提交失败!'); } } $this->render('update', array('model' => $model)); }