getInstance() public static method

The file should be uploaded using [[\yii\widgets\ActiveField::fileInput()]].
See also: getInstanceByName()
public static getInstance ( Model $model, string $attribute ) : UploadedFile
$model yii\base\Model the data model
$attribute string the attribute name. The attribute name may contain array indexes. For example, '[1]file' for tabular file uploading; and 'file[1]' for an element in a file array.
return UploadedFile the instance of the uploaded file. Null is returned if no file is uploaded for the specified model attribute.
Beispiel #1
1
 function beforeSave($insert)
 {
     if (parent::beforeSave($insert)) {
         $file = UploadedFile::getInstance($this, 'image');
         if ($file && $file->error === UPLOAD_ERR_OK) {
             // Ищем, есть ли уже такой загруженный файл
             $file_model = Files::findOne(['hash' => md5_file($file->tempName)]);
             if ($file_model) {
                 $file_model->repeats++;
             } else {
                 $file_model = new Files();
                 $file_model->saveImageFile($file);
                 $file_model->repeats = 1;
             }
             $file_model->save();
             $this->file_id = $file_model->id;
         } else {
             $this->addError('image', 'Невозможно загрузить файл');
             return false;
         }
         return true;
     } else {
         return false;
     }
 }
 public function actionAvatar()
 {
     if (\Yii::$app->request->get('do') == 'edit') {
         $model = new AvatarForm();
         if (\Yii::$app->request->isPost) {
             $model->avatar = UploadedFile::getInstance($model, 'avatar');
             if ($model->validate()) {
                 $uploadDir = 'upload/avatar/' . date('Ym');
                 if (!file_exists($uploadDir)) {
                     mkdir($uploadDir);
                 }
                 $uploadFile = $uploadDir . '/' . $model->avatar->name;
                 $model->avatar->saveAs($uploadFile);
                 $model->avatar->name = '/' . $uploadFile;
                 list($width, $height) = getimagesize($uploadFile);
                 return $this->ajaxReturn(['avatar' => $model->avatar->name, 'width' => $width, 'height' => $height]);
             }
         }
         return $this->render('/user/profile/avatar_edit', ['model' => $model]);
     } else {
         if (\Yii::$app->request->get('do') == 'save') {
             $avatar = \Yii::$app->request->post('avatar');
             $width = intval(\Yii::$app->request->post('width'));
             $height = intval(\Yii::$app->request->post('height'));
             $img = $this->thumb($avatar, $width, $height);
             $coords = explode(',', \Yii::$app->request->post('coords'));
             $img = $this->crop($img, $coords[0], $coords[1], [$coords[2], $coords[3]]);
             Profile::saveAvatar($img);
             return $this->ajaxReturn(['msg' => '保存成功']);
         }
     }
     return $this->redirect('/user/profile/avatar');
 }
Beispiel #3
0
 public function actionCreate()
 {
     $model = new Import();
     if ($model->load(Yii::$app->request->post())) {
         $file_path = \yii\web\UploadedFile::getInstance($model, 'file_path');
         if (!empty($file_path)) {
             $model->file_path = \yii\web\UploadedFile::getInstance($model, 'file_path');
             $ext = FileHelper::getExtention($model->file_path);
             if (!empty($ext)) {
                 $fileDir = Yii::$app->controller->module->id . '/' . date('Y/m/d/');
                 $fileName = uniqid() . StringHelper::asUrl(Yii::$app->controller->module->id) . '.' . $ext;
                 $folder = Yii::$app->params['uploadPath'] . '/' . Yii::$app->params['uploadDir'] . '/' . $fileDir;
                 FileHelper::createDirectory($folder);
                 $model->file_path->saveAs($folder . $fileName);
                 $model->file_path = $fileDir . $fileName;
             }
         }
         if ($model->save()) {
             return $this->redirect(['update', 'id' => (string) $model->_id]);
         }
     }
     Yii::$app->view->title = Yii::t($this->module->id, 'Create');
     Yii::$app->view->params['breadcrumbs'][] = ['label' => Yii::t($this->module->id, 'Import'), 'url' => ['index']];
     Yii::$app->view->params['breadcrumbs'][] = Yii::$app->view->title;
     return $this->render('create', ['model' => $model]);
 }
Beispiel #4
0
 public function afterUpdate()
 {
     try {
         if ($this->seoText->load(Yii::$app->request->post())) {
             $this->seoText->setAttributes(['_image' => UploadedFile::getInstance($this->seoText, '_image')]);
             // if(!$this->seoText->isEmpty()){
             if ($this->seoText->save()) {
                 if ($this->seoText->_image) {
                     $old = $this->seoText->ogImage;
                     $photo = new Photo();
                     $photo->class = get_class($this->seoText);
                     $photo->item_id = $this->seoText->seotext_id;
                     $photo->image = $this->seoText->_image;
                     if ($photo->image && $photo->validate(['image'])) {
                         $photo->image = Image::upload($photo->image, 'photos', Photo::PHOTO_MAX_WIDTH);
                         if ($photo->image) {
                             if ($photo->save()) {
                                 $old->delete();
                             } else {
                                 @unlink(Yii::getAlias('@webroot') . str_replace(Url::base(true), '', $photo->image));
                             }
                         } else {
                         }
                     }
                 }
             }
         }
     } catch (UnknownMethodException $e) {
     }
 }
 public function actionIndex()
 {
     $model = new UploadForm();
     if (Yii::$app->request->isPost) {
         $model->file = UploadedFile::getInstance($model, 'file');
         $ext = $model->file->extension;
         $file_name = $model->file->baseName . '.' . $model->file->extension;
         if ($model->upload()) {
             if ($ext == 'csv') {
                 $erros = $this->ConverterCSV($file_name);
             }
             if ($ext == 'txt') {
                 $erros = $this->ConverterTXT($file_name);
             }
             if ($erros == NULL) {
                 $link = Html::a('Ver em produtos', ['/produto'], ['class' => 'btn btn-primary']);
                 \Yii::$app->getSession()->setFlash('success', 'Dados importados! ' . $link . '');
             } else {
                 if (is_array($erros)) {
                     $texto_erro = "";
                     foreach ($erros as $erro) {
                         $texto_erro .= $erro . '<br/>';
                     }
                     \Yii::$app->getSession()->setFlash('error', $texto_erro);
                 }
             }
         }
     }
     return $this->render('index', ['model' => $model]);
 }
Beispiel #6
0
 public function actionIndex()
 {
     $id = Yii::$app->request->get('id');
     $modelName = Yii::$app->request->get('model');
     if (!empty($id)) {
         $model = $modelName::findOne($id);
         if ($model) {
             //                $model->gallery = \yii\web\UploadedFile::getInstance($model, 'gallery');
             $image = \yii\web\UploadedFile::getInstance($model, 'gallery');
             $ext = FileHelper::getExtention($image);
             if (!empty($ext)) {
                 // Thêm validate ext ____________________________
                 $file_id = uniqid();
                 $fileDir = Yii::$app->controller->module->id . '/' . date('Y/m/d/');
                 $fileName = $file_id . '.' . $ext;
                 $folder = Yii::$app->params['uploadPath'] . '/' . Yii::$app->params['uploadDir'] . '/' . $fileDir;
                 FileHelper::createDirectory($folder);
                 $image->saveAs($folder . $fileName);
                 $output = ["out" => ['file_id' => $file_id, 'item_id' => Yii::$app->controller->module->id]];
                 if (empty($model->gallery)) {
                     $model->gallery = $fileDir . $fileName;
                 } else {
                     $model->gallery .= ',' . $fileDir . $fileName;
                 }
                 $model->save();
                 echo json_encode($output);
             }
         }
     }
 }
Beispiel #7
0
 public function actionEdit($id)
 {
     if (!($model = Category::findOne($id))) {
         return $this->redirect(['/admin/catalog']);
     }
     if ($model->load(Yii::$app->request->post())) {
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         } else {
             if (isset($_FILES) && $this->module->settings['categoryThumb']) {
                 $model->thumb = UploadedFile::getInstance($model, 'thumb');
                 if ($model->thumb && $model->validate(['thumb'])) {
                     $model->thumb = Image::upload($model->thumb, 'catalog', $this->module->settings['categoryThumbWidth'], $this->module->settings['categoryThumbHeight'], $this->module->settings['categoryThumbCrop']);
                 } else {
                     $model->thumb = $model->oldAttributes['thumb'];
                 }
             }
             if ($model->save()) {
                 $this->flash('success', Yii::t('easyii/catalog', 'Category updated'));
             } else {
                 $this->flash('error', Yii::t('easyii', 'Update error. {0}', $model->formatErrors()));
             }
             return $this->refresh();
         }
     } else {
         return $this->render('edit', ['model' => $model]);
     }
 }
 /**
  * Attaches uploaded file to owner.
  */
 public function beforeValidate()
 {
     if (!($file = UploadedFile::getInstance($this->owner, $this->fileField))) {
         return true;
     }
     $this->owner->{$this->fileField} = $file;
 }
 /**
  * 上传商品图片
  */
 public function actionProductpic()
 {
     $user_id = \Yii::$app->user->getId();
     $p_params = Yii::$app->request->get();
     $product = Product::findOne($p_params['id']);
     if (!$product) {
         throw new NotFoundHttpException(Yii::t('app', 'Page not found'));
     }
     $picture = new UploadForm();
     $picture->file = UploadedFile::getInstance($product, 'product_s_img');
     if ($picture->file !== null && $picture->validate()) {
         Yii::$app->response->getHeaders()->set('Vary', 'Accept');
         Yii::$app->response->format = Response::FORMAT_JSON;
         $response = [];
         if ($picture->productSave()) {
             $response['files'][] = ['name' => $picture->file->name, 'type' => $picture->file->type, 'size' => $picture->file->size, 'url' => '/' . $picture->getImageUrl(), 'thumbnailUrl' => '/' . $picture->getOImageUrl(), 'deleteUrl' => Url::to(['/uploadfile/deletepropic', 'id' => $picture->getID()]), 'deleteType' => 'POST'];
         } else {
             $response[] = ['error' => Yii::t('app', '上传错误')];
         }
         @unlink($picture->file->tempName);
     } else {
         if ($picture->hasErrors()) {
             $response[] = ['error' => '上传错误'];
         } else {
             throw new HttpException(500, Yii::t('app', '上传错误'));
         }
     }
     return $response;
 }
 /**
  * Creates a new User model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new User();
     try {
         if ($model->load($_POST)) {
             $model->password = md5($model->password);
             $image = UploadedFile::getInstance($model, 'photo_url');
             if ($image != NULL) {
                 # store the source file name
                 $model->photo_url = $image->name;
                 $extension = end(explode(".", $image->name));
                 # generate a unique file name
                 $model->photo_url = Yii::$app->security->generateRandomString() . ".{$extension}";
                 # the path to save file
                 $path = Yii::getAlias("@app/web/uploads/") . $model->photo_url;
                 $image->saveAs($path);
             } else {
                 $model->photo_url = "default.png";
             }
             $model->save();
             return $this->redirect(Url::previous());
         } elseif (!\Yii::$app->request->isPost) {
             $model->load($_GET);
         }
     } catch (\Exception $e) {
         $msg = isset($e->errorInfo[2]) ? $e->errorInfo[2] : $e->getMessage();
         $model->addError('_exception', $msg);
     }
     return $this->render('create', ['model' => $model]);
 }
Beispiel #11
0
 public function actionUpload($model, $primaryKey)
 {
     $results = [];
     $modelImage = new Image();
     $modelImage->model = $model;
     $modelImage->primaryKey = $primaryKey;
     $filePath = $modelImage->getFilePath();
     if (Yii::$app->request->isPost) {
         $modelImage->file = UploadedFile::getInstance($modelImage, 'file');
         if ($modelImage->file && $modelImage->validate()) {
             $filename = $modelImage->file->name;
             $modelImage->src = $filename;
             $modelImage->position = $modelImage->nextPosition;
             $modelImage->save();
             $image = \Yii::$app->image->load($modelImage->file->tempName);
             $image->resize(2592, 1728, \yii\image\drivers\Image::AUTO);
             if ($image->save($filePath . '/' . $filename)) {
                 $imagePath = $filePath . '/' . $filename;
                 $result = ['name' => $filename, 'size' => filesize($filePath . '/' . $filename), 'url' => $imagePath, 'thumbnailUrl' => $modelImage->resize('100x100'), 'deleteUrl' => Url::to(['/core/image/delete', 'id' => $modelImage->id]), 'deleteType' => "DELETE"];
                 $results[] = $result;
             }
         } else {
             $results[] = (object) [$modelImage->file->name => false, 'error' => strip_tags(Html::error($modelImage, 'file')), 'extension' => $modelImage->file->extension, 'type' => $modelImage->file->type];
         }
     }
     echo json_encode((object) ['files' => $results]);
 }
Beispiel #12
0
 public function actionImport()
 {
     $field = ['fileImport' => 'File Import'];
     $modelImport = DynamicModel::validateData($field, [[['fileImport'], 'required'], [['fileImport'], 'file', 'extensions' => 'xls,xlsx', 'maxSize' => 1024 * 1024]]);
     if (Yii::$app->request->post()) {
         $modelImport->fileImport = \yii\web\UploadedFile::getInstance($modelImport, 'fileImport');
         if ($modelImport->fileImport && $modelImport->validate()) {
             $inputFileType = \PHPExcel_IOFactory::identify($modelImport->fileImport->tempName);
             $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
             $objPHPExcel = $objReader->load($modelImport->fileImport->tempName);
             $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
             $baseRow = 2;
             while (!empty($sheetData[$baseRow]['A'])) {
                 $model = new Mahasiswa();
                 $model->nama = (string) $sheetData[$baseRow]['B'];
                 $model->nim = (string) $sheetData[$baseRow]['C'];
                 $model->save();
                 //die(print_r($model->errors));
                 $baseRow++;
             }
             Yii::$app->getSession()->setFlash('success', 'Success');
         } else {
             Yii::$app->getSession()->setFlash('error', 'Error');
         }
     }
     return $this->redirect(['index']);
 }
 public function add()
 {
     if ($this->validate()) {
         $organization = new Organizations();
         $organization->official_name = $this->official_name;
         $organization->nice_name = $this->nice_name;
         $organization->cyr_name = $this->cyr_name;
         $organization->overdraft_limit = $this->overdraft;
         $organization->outbalance_limit = $this->outbalance;
         $organization->ratio = $this->ratio;
         $logo_file = UploadedFile::getInstance($this, 'logo');
         if ($logo_file) {
             $file_name = $logo_file->baseName . '.' . $logo_file->extension;
             $organization->logo = $file_name;
         }
         if ($organization->save()) {
             if ($logo_file) {
                 $folder_path = Yii::$app->params['org_img_path'] . '/' . $organization->id;
                 mkdir($folder_path);
                 $logo_file->saveAs($folder_path . '/' . $file_name);
             }
             $this->addOwnersRelations($organization->id);
             return true;
         }
     }
     return false;
 }
 public function upload($attribute)
 {
     if ($uploadImage = UploadedFile::getInstance($this->owner, $attribute)) {
         if (!$this->owner->isNewRecord) {
             $this->delete($attribute);
         }
         $croppingFileName = md5($uploadImage->name . $this->quality . filemtime($uploadImage->tempName));
         $croppingFileExt = strrchr($uploadImage->name, '.');
         $croppingFileDir = substr($croppingFileName, 0, 2);
         $croppingFileBasePath = Yii::getAlias($this->basePath) . $this->baseDir;
         if (!is_dir($croppingFileBasePath)) {
             mkdir($croppingFileBasePath, 0755, true);
         }
         $croppingFilePath = Yii::getAlias($this->basePath) . $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir;
         if (!is_dir($croppingFilePath)) {
             mkdir($croppingFilePath, 0755, true);
         }
         $croppingFile = $croppingFilePath . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt;
         $cropping = $_POST[$attribute . '-cropping'];
         $imageTmp = Image::getImagine()->open($uploadImage->tempName);
         $imageTmp->rotate($cropping['dataRotate']);
         $image = Image::getImagine()->create($imageTmp->getSize());
         $image->paste($imageTmp, new Point(0, 0));
         $point = new Point($cropping['dataX'], $cropping['dataY']);
         $box = new Box($cropping['dataWidth'], $cropping['dataHeight']);
         $image->crop($point, $box);
         $image->save($croppingFile, ['quality' => $this->quality]);
         $this->owner->{$attribute} = $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt;
     } elseif (isset($_POST[$attribute . '-remove']) && $_POST[$attribute . '-remove']) {
         $this->delete($attribute);
     } elseif (isset($this->owner->oldAttributes[$attribute])) {
         $this->owner->{$attribute} = $this->owner->oldAttributes[$attribute];
     }
 }
Beispiel #15
0
 public function actionEdit($id)
 {
     $model = Carousel::findOne($id);
     if ($model === null) {
         $this->flash('error', Yii::t('easyii', 'Not found'));
         return $this->redirect(['/admin/' . $this->module->id]);
     }
     if ($model->load(Yii::$app->request->post())) {
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         } else {
             if ($fileInstanse = UploadedFile::getInstance($model, 'image')) {
                 $model->image = $fileInstanse;
                 if ($model->validate(['image'])) {
                     $model->image = Image::upload($model->image, 'carousel');
                 } else {
                     $this->flash('error', Yii::t('easyii', 'Update error. {0}', $model->formatErrors()));
                     return $this->refresh();
                 }
             } else {
                 $model->image = $model->oldAttributes['image'];
             }
             if ($model->save()) {
                 $this->flash('success', Yii::t('easyii/carousel', 'Carousel updated'));
             } else {
                 $this->flash('error', Yii::t('easyii/carousel', 'Update error. {0}', $model->formatErrors()));
             }
             return $this->refresh();
         }
     } else {
         return $this->render('edit', ['model' => $model]);
     }
 }
Beispiel #16
0
 public function actionProfile()
 {
     $model = $this->finder->findProfileById(Yii::$app->user->identity->getId());
     $this->performAjaxValidation($model);
     if ($model->load(Yii::$app->request->post())) {
         $model->fileProfile = \yii\web\UploadedFile::getInstance($model, 'fileProfile');
         $model->fileHeader = \yii\web\UploadedFile::getInstance($model, 'fileHeader');
         $save_fileProfile = '';
         $save_fileHeader = '';
         if ($model->fileProfile) {
             $imagepath = 'uploads/profile/';
             // Create folder under web/uploads/logo
             $model->image_profile = $imagepath . rand(10, 100) . '-' . $model->fileProfile->name;
             $save_fileProfile = 1;
         }
         if ($model->fileHeader) {
             $imagepath = 'uploads/header/';
             $model->image_header = $imagepath . rand(10, 100) . '-' . $model->fileHeader->name;
             $save_fileHeader = 1;
         }
         if ($model->save()) {
             if ($save_fileProfile) {
                 $model->fileProfile->saveAs($model->image_profile);
             }
             if ($save_fileHeader) {
                 $model->fileHeader->saveAs($model->image_header);
             }
             Yii::$app->getSession()->setFlash('success', Yii::t('user', 'Your profile has been updated'));
             return $this->refresh();
         }
     }
     return $this->render('profile', ['model' => $model]);
     //return parent::actionProfile();
 }
 /**
  * Creates a new Photos model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Photos();
     if ($model->load(Yii::$app->request->post())) {
         $model->file = UploadedFile::getInstance($model, 'file');
         $fileName = uniqid() . '.' . $model->file->extension;
         if ($model->file) {
             $model->file->saveAs('pics/' . $fileName);
             $model->name = $fileName;
             $model->created_at = date('Y-m-d H:i:s');
             if ($model->isAvatar) {
                 $model->relative->setImage($fileName);
                 $model->relative->save();
             }
             //                $size = getimagesize('pics/'. $fileName);
             //                $ratio = $size[0]/$size[1];
             //                $width = 30;
             //                $height = round($width/$ratio);
             //                Image::thumbnail('pics/'. $fileName, $width, $height)->save('/pics/thumb/30_'.$fileName);
             $model->save();
             return $this->redirect(['/relatives/view', 'id' => $model->relative_id]);
         } else {
             return $this->render('create', ['model' => $model]);
         }
     } else {
         $relative_id = $_REQUEST['relative_id'];
         $model->relative_id = $relative_id;
         return $this->render('create', ['model' => $model]);
     }
 }
Beispiel #18
0
 public function actionUpload()
 {
     $model = new \backend\models\Saleorderline();
     if (\Yii::$app->request->post()) {
         $uploaded = UploadedFile::getInstance($model, 'upfile');
         if (!empty($uploaded)) {
             $upfiles = time() . "." . $uploaded->getExtension();
             // $uploaded->saveAs('../../uploads/'.$upfiles);
             $handle = fopen('../../uploads/' . $upfiles, 'r');
             while (($fileop = fgetcsv($handle, 1000, ",")) !== false) {
                 $model = new \backend\models\Saleorderline();
                 $model->saleid = 'SO0001';
                 $model->saleline = $fileop[0];
                 $model->partno = $fileop[1];
                 //  echo $name."<BR />";
                 // $age = $fileop[1];
                 //$location = $fileop[2];
                 //print_r($fileop);exit();
                 //                        $sql = "INSERT INTO details(name, age, location) VALUES ('$name', '$age', '$location')";
                 //                        $query = Yii::$app->db->createCommand($sql)->execute();
                 $model->save();
             }
             fclose($handle);
         }
     }
 }
Beispiel #19
0
 public function save()
 {
     $model = Books::findOne($this->id);
     $fileInstance = UploadedFile::getInstance($this, self::FIELD_PREVIEW);
     if ($fileInstance) {
         $filePath = 'images/' . $fileInstance->baseName . '.' . $fileInstance->extension;
         $model->preview = $fileInstance->baseName . '.' . $fileInstance->extension;
         $fileInstance->saveAs($filePath, false);
         $imagine = new Gd\Imagine();
         try {
             $filePath = 'images/preview_' . $fileInstance->baseName . '.' . $fileInstance->extension;
             $img = $imagine->open($fileInstance->tempName);
             $size = $img->getSize();
             if ($size->getHeight() > $this->imageSizeLimit['width'] || $size->getWidth() > $this->imageSizeLimit['height']) {
                 $img->resize(new Box($this->imageSizeLimit['width'], $this->imageSizeLimit['height']));
             }
             $img->save($filePath);
             //
         } catch (\Imagine\Exception\RuntimeException $ex) {
             $this->addError(self::FIELD_PREVIEW, 'Imagine runtime exception: ' . $ex->getMessage());
             return FALSE;
         }
     }
     if (!$this->validate()) {
         return false;
     }
     $model->name = $this->name;
     $model->author_id = $this->author_id;
     $model->date = DateTime::createFromFormat('d/m/Y', $this->date)->format('Y-m-d');
     $model->date_update = new Expression('NOW()');
     $model->save();
     return true;
 }
Beispiel #20
0
 public static function saveImage($model)
 {
     $model->date = date('Y-m-d');
     $maxId = Products::find()->select('max(id)')->scalar();
     $imageName = $maxId + 1;
     // (uniqid('img_')-как вариант, без нагрузки на бд)лучше вариант чем с датой, primary key всегда будет
     // уникальным + запрос вроде не сложный на выборку поскольку primary индексированый и взять максимальное
     // не составит большую нагрузку на бд
     $model->photo = UploadedFile::getInstance($model, 'photo');
     $fullName = Yii::getAlias('@webroot') . '/photos/' . $imageName . '.' . $model->photo->extension;
     $model->photo->saveAs($fullName);
     $img = Image::getImagine()->open($fullName);
     $size = $img->getSize();
     $ratio = $size->getWidth() / $size->getHeight();
     $height = round(Products::IMAGE_WIDTH / $ratio);
     $box = new Box(Products::IMAGE_WIDTH, $height);
     $img->resize($box)->save(Yii::getAlias('@webroot') . '/thumbnails/' . $imageName . '.' . $model->photo->extension);
     $model->thumbnail = '/thumbnails/' . $imageName . '.' . $model->photo->extension;
     $model->photo = '/photos/' . $imageName . '.' . $model->photo->extension;
     $save = $model->save();
     if ($save) {
         return true;
     } else {
         die('product model was not save');
     }
 }
Beispiel #21
0
 public function actionImage($id, $maxWidth, $thumbWidth, $thumbHeight = null, $thumbCrop = true)
 {
     $success = null;
     if ($photo = Photo::findOne($id)) {
         $oldImage = $photo->image;
         $oldThumb = $photo->thumb;
         $photo->image = UploadedFile::getInstance($photo, 'image');
         if ($photo->image && $photo->validate(['image'])) {
             $photo->image = Image::upload($photo->image, 'photos', $maxWidth);
             if ($photo->image) {
                 $photo->thumb = Image::createThumbnail($photo->image, $thumbWidth, $thumbHeight, $thumbCrop);
                 if ($photo->save()) {
                     @unlink(Yii::getAlias('@webroot') . $oldImage);
                     @unlink(Yii::getAlias('@webroot') . $oldThumb);
                     $success = ['message' => Yii::t('easyii', 'Photo uploaded'), 'photo' => ['thumb' => $photo->thumb, 'image' => $photo->image]];
                 } else {
                     @unlink(Yii::getAlias('@webroot') . $photo->image);
                     @unlink(Yii::getAlias('@webroot') . $photo->thumb);
                     $this->error = Yii::t('easyii', 'Update error. {0}', $photo->formatErrors());
                 }
             } else {
                 $this->error = Yii::t('easyii', 'File upload error. Check uploads folder for write permissions');
             }
         } else {
             $this->error = Yii::t('easyii', 'File is incorrect');
         }
     } else {
         $this->error = Yii::t('easyii', 'Not found');
     }
     return $this->formatResponse($success);
 }
 /**
  * Creates a new Companies model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     if (Yii::$app->user->can('create-company')) {
         $model = new Companies();
         $branch = new Branches();
         if ($model->load(Yii::$app->request->post()) && $branch->load(Yii::$app->request->post())) {
             // get the instance of the uploaded file
             $imageName = $model->company_name;
             if (!empty($model->file)) {
                 $model->file = UploadedFile::getInstance($model, 'file');
                 $model->file->saveAs('uploads/' . $imageName . '.' . $model->file->extension);
                 // save the path in the db column
                 $model->logo = 'uploads/' . $imageName . '.' . $model->file->extension;
             }
             $model->company_created_date = date('Y-m-d h:m:s');
             $model->save();
             // save the branch
             $branch->companies_company_id = $model->company_id;
             $branch->branch_created_date = date('Y-m-d h:m:s');
             $branch->save();
             return $this->redirect(['view', 'id' => $model->company_id]);
         } else {
             return $this->render('create', ['model' => $model, 'branch' => $branch]);
         }
     } else {
         throw new ForbiddenHttpException();
     }
 }
 public function actionEdit($id)
 {
     if (!($model = Item::findOne($id))) {
         return $this->redirect(['/admin/' . $this->module->id]);
     }
     if ($model->load(Yii::$app->request->post())) {
         if (Yii::$app->request->isAjax) {
             Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
             return ActiveForm::validate($model);
         } else {
             if (isset($_FILES) && $this->module->settings['articleThumb']) {
                 $model->image = UploadedFile::getInstance($model, 'image');
                 if ($model->image && $model->validate(['image'])) {
                     $model->image = Image::upload($model->image, 'sections');
                 } else {
                     $model->image = $model->oldAttributes['image'];
                 }
             }
             if ($model->save()) {
                 $this->flash('success', Yii::t('easyii/sections', 'Article updated'));
                 return $this->redirect(['/admin/' . $this->module->id . '/items/edit', 'id' => $model->primaryKey]);
             } else {
                 $this->flash('error', Yii::t('easyii', 'Update error. {0}', $model->formatErrors()));
                 return $this->refresh();
             }
         }
     } else {
         return $this->render('edit', ['model' => $model]);
     }
 }
Beispiel #24
0
 /**
  * Updates an existing Books model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     $preview = $model->preview;
     $dir = Yii::getAlias('@uploads');
     if ($model->load(Yii::$app->request->post())) {
         $model->date_update = date('Y-m-d');
         $model->preview = UploadedFile::getInstance($model, 'preview');
         if ($model->preview && $model->validate()) {
             $path = $dir . '/' . $model->generateUniqueFilename() . '.' . $model->preview->extension;
             $model->preview->saveAs($path);
             $model->preview = $path;
             unlink($preview);
         } else {
             $model->preview = $preview;
         }
         if ($model->save()) {
             $url = 'index';
             if (count(Yii::$app->request->get()) > 1) {
                 $url = 'index' . '?' . explode('?', Yii::$app->request->getAbsoluteUrl())[1];
             }
             return $this->redirect([$url]);
         }
     }
     return $this->render('update', ['model' => $model]);
 }
 public function actionIndex()
 {
     //没登录就回到主页
     if (Yii::$app->user->isGuest) {
         return $this->render('/site/index');
     }
     //没加入队伍就到/team/error页面
     if (User::findByUsername(Yii::$app->user->identity->username)->teamname == "") {
         return $this->render('/team/error', ['message' => '<h2>你还没有加入任何一个战队呢!</h2>']);
     }
     $myteamname = User::findByUsername(Yii::$app->user->identity->username)->teamname;
     $myteam = Team::findOne(['teamname' => $myteamname]);
     //上传文件
     $model = new UploadForm();
     if (Yii::$app->request->isPost) {
         if ($myteam->uploaded_time < 50) {
             $model->sourcecode = UploadedFile::getInstance($model, 'sourcecode');
             if ($id = $model->upload_first_round()) {
                 return $this->render('uploadsuccess');
             }
         }
     }
     $alreadysubmit = Firstroundcodes::find()->where(array('teamid' => $myteam->id))->exists();
     //上传文件$model,
     return $this->render('index', ['model' => $model, 'alreadysubmit' => $alreadysubmit, 'myteam' => $myteam]);
     //,'indexs'=>$indexs]);
 }
Beispiel #26
0
 /**
  * Updates an existing Bp24h model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     $upload = new UploadForm();
     $bp24 = new Bp24h();
     $_24hdata = $bp24->pull24hoursdata($id);
     $pid = $model->fk_person;
     $persondetails = \app\models\Participant::findOne(['pk_person' => $pid]);
     if ($model->load(Yii::$app->request->post())) {
         $model->altered = 1;
         $persondetails->filtered = $persondetails->filtered + 1;
         if ($model->wasuploaded != 1) {
             $model->file = UploadedFile::getInstance($model, 'file');
             $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
             $model->wasuploaded = 1;
         }
         $persondetails->save(FALSE);
         $model->save(FALSE);
         if (!empty($model->file)) {
             return $this->redirect(['bp24h/uploadexcel', 'fkperson' => $model->fk_person, 'idbp24' => $model->idbp24, 'name' => $model->file->baseName]);
         } else {
             Yii::$app->session->setFlash('success', 'The record has been updated successfully');
             return $this->redirect(['participant/index']);
         }
     } else {
         return $this->render('update', ['model' => $model, 'upload' => $upload, 'dataProvider' => $_24hdata, 'persondetails' => $persondetails]);
     }
 }
 public function actionReg()
 {
     $model = new RegForm();
     $error = null;
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         $user = new Users();
         $user->login = Html::encode($model->login);
         $user->password = md5($model->password);
         $user->name = Html::encode($model->name);
         $user->email = Html::encode($model->email);
         $user->phone = Html::encode($model->phone);
         if (UploadedFile::getInstance($model, 'photo')) {
             $model->photo = UploadedFile::getInstance($model, 'photo');
             $model->photo->saveAs('img/photo/' . $model->photo->baseName . '.' . $model->photo->extension);
             $photo = 'img/photo/' . $model->photo->baseName . '.' . $model->photo->extension;
             $user->photo = $photo;
         }
         $uc = new UserClass();
         if ($uc->isUniqueLogin($user->login)) {
             $user->save();
             return $this->render('regsuccess');
         } else {
             $error = 'Такой логин уже существует';
         }
     }
     return $this->render('reg', ['model' => $model, 'error' => $error]);
 }
 /**
  * Creates a new Companies model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     if (Yii::$app->user->can('create-company')) {
         $company = new Companies();
         $branch = new Branches();
         if ($company->load(Yii::$app->request->post()) && $branch->load(Yii::$app->request->post())) {
             // print_r($company);
             // print_r($branch);
             // die;
             // get the instance of the uploaded file
             $imageName = $company->company_name;
             $company->file = UploadedFile::getInstance($company, 'file');
             $company->file->saveAs('uploads/' . $imageName . '.' . $company->file->extension);
             // save the path in the db column
             $company->logo = 'uploads/' . $imageName . '.' . $company->file->extension;
             $company->company_created_date = date('Y-m-d h:i:s a');
             $company->save();
             // save branches
             $branch->branch_created_date = date('Y-m-d h:i:s a');
             $branch->save();
             return $this->redirect(['view', 'id' => $company->company_id]);
         } else {
             return $this->render('create', ['company' => $company, 'branch' => $branch]);
         }
     } else {
         throw new ForbiddenHttpException();
     }
 }
 /**
  * Updates an existing Grades model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate()
 {
     $username = Yii::$app->user->identity->username;
     $users = User::find()->all();
     $grades = Grades::find()->all();
     $model = new Grades();
     foreach ($users as $user) {
         foreach ($grades as $grade) {
             if ($user->username == $username && $user->id == $grade->grade_scholar_id) {
                 $id = $grade->grade_id;
                 $model = $this->findModel($id);
                 if ($model->load(Yii::$app->request->post()) && $model->save()) {
                     $fileName = $model->grade_id . "gradeform";
                     $model->file = UploadedFile::getInstance($model, 'file');
                     if ($model->file != null) {
                         $model->file->saveAs('GradeForm/' . $fileName . '.' . $model->file->extension);
                         $model->grade_grade_form = 'GradeForm/' . $fileName . '.' . $model->file->extension;
                     }
                     $model->save();
                     return $this->redirect(['view', 'id' => $model->grade_id]);
                     return $this->redirect(['view', 'id' => $model->grade_id]);
                 } else {
                     return $this->render('update', ['model' => $model]);
                 }
             }
         }
     }
 }
 /**
  * Updates an existing Task model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     $old_attachment = $model->attachment;
     if ($model->task_from !== Yii::$app->user->id) {
         return $this->redirect(['index']);
     }
     if (Yii::$app->request->isPost) {
         if ($model->load(Yii::$app->request->post())) {
             $model->attachment = UploadedFile::getInstance($model, 'attachment');
             $model->task_start = date('Y-m-d', strtotime($model->task_start));
             $model->task_end = date('Y-m-d', strtotime($model->task_end));
             if ($model->attachment) {
                 $fileName = sprintf('%s.%s', $model->task_to . time(), $model->attachment->extension);
                 $model->attachment->saveAs('uploads/' . $fileName);
                 $model->attachment = $fileName;
             } else {
                 $model->attachment = $old_attachment;
             }
             if ($model->validate() && $model->save()) {
                 // if new attachment diffrent from old attachment
                 // delete old attachment
                 if (strcmp($model->attachment, $old_attachment) !== 0) {
                     @unlink('uploads/' . $old_attachment);
                 }
                 Yii::$app->getSession()->setFlash('success', Yii::t('app', 'Data Tugas Berhasil Diubah'));
                 return $this->redirect(['index']);
             } else {
                 Yii::$app->getSession()->setFlash('error', Yii::t('app', 'Data Tugas Gagal Diubah'));
             }
         }
     }
     return $this->render('update', ['model' => $model]);
 }