getInstances() public static method

Returns all uploaded files for the given model attribute.
public static getInstances ( 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 tabular file uploading, e.g. '[1]file'.
return UploadedFile[] array of UploadedFile objects. Empty array is returned if no available file was found for the given attribute.
 /**
  * Creates a new Sucursal model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Sucursal();
     $model->create_user = Yii::$app->user->getId();
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         $saved = true;
         $model->imagenes = UploadedFile::getInstances($model, 'imagenes');
         foreach ($model->imagenes as $imagen) {
             $image = new Imagen();
             $rnd = rand(0, 99999999);
             $path = Yii::$app->basePath . '/web/images';
             if (!file_exists($path)) {
                 mkdir($path, 0777);
             }
             $path = $path . '/Sucursal';
             if (!file_exists($path)) {
                 mkdir($path, 0777);
             }
             $path = $path . '/' . $model->id;
             if (!file_exists($path)) {
                 mkdir($path, 0777);
             }
             $imagen->saveAs($path . '/' . $rnd . '.' . $imagen->extension);
             $image->ur_imagen = $rnd . '.' . $imagen->extension;
             $image->save();
         }
         if ($saved) {
             return $this->redirect(['view', 'id' => $model->id]);
         }
     } else {
         return $this->render('create', ['model' => $model]);
     }
 }
Beispiel #2
0
 public function actionIndex($id, $tagId = null)
 {
     $project = $this->loadModel('app\\models\\Project', $id);
     $this->view->params['appSettings'] = ['app_name' => $project->title];
     if (!\Yii::$app->user->can('viewProject', ['project' => $project])) {
         throw new ForbiddenHttpException('Access denied');
     }
     $model = new Files();
     if (($files = UploadedFile::getInstances($model, 'file')) && !\Yii::$app->user->isGuest) {
         foreach ($files as $file) {
             $model = new Files();
             $model->file = $file->name;
             $model->project_id = $project->id;
             $model->tags = $_POST['Files']['tags'];
             if ($model->save()) {
                 $file->saveAs($this->_getFolder($model) . $file->name);
             } else {
                 die(var_dump($file->getErrors()));
             }
         }
     }
     $searchModel = new FilesSearch();
     $searchModel->project_id = (int) $project->id;
     if (isset($tagId)) {
         $searchModel->tagId = $tagId;
     }
     $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
     $model->tags = null;
     return $this->render('index', ['model' => $model, 'dataProvider' => $dataProvider, 'searchModel' => $searchModel, 'project' => $project, 'tagId' => $tagId]);
 }
 /**
  * Upload Files Before Save.
  *
  * @return void
  * @version 1.0
  */
 public function beforeSave()
 {
     $result = [];
     //Array of Images data.
     $owner = $this->owner;
     // If attributes are not empty.
     if ($this->attributes) {
         foreach ($this->attributes as $attr) {
             // If Isset attribute in our Model.
             if (isset($owner->{$attr['attribute']}) && ($path = $this->getPath($attr))) {
                 $files = UploadedFile::getInstances($owner, $attr['attribute']);
                 // If array with files is not empty.
                 if ($files) {
                     foreach ($files as $key => $file) {
                         $url = Url::to($path . DIRECTORY_SEPARATOR . $file->name);
                         if ($file->saveAs($url)) {
                             $result[$attr['attribute']][$key] = ['url' => $url, 'file' => $file];
                             // If it is image then crop it.
                             if (getimagesize($url) && isset($attr['sizes'])) {
                                 $result[$attr['attribute']][$key]['cropped'][] = $this->crop($attr, $file, Url::to($path));
                             }
                         }
                     }
                     $this->owner->{$attr['attribute']} = $result[$attr['attribute']];
                 }
             }
         }
     }
 }
 public function actionUpload()
 {
     $model = new UploadForm();
     $model->file = UploadedFile::getInstances($model, 'file');
     if ($model->rules()[0]['maxFiles'] == 1 && sizeof($model->file) == 1) {
         $model->file = $model->file[0];
     }
     if ($model->file && $model->validate()) {
         $result['uploadedFiles'] = [];
         if (is_array($model->file)) {
             foreach ($model->file as $file) {
                 $path = $this->getModule()->getUserDirPath() . DIRECTORY_SEPARATOR . $file->name;
                 $file->saveAs($path);
                 $result['uploadedFiles'][] = $file->name;
             }
         } else {
             $path = $this->getModule()->getUserDirPath() . DIRECTORY_SEPARATOR . $model->file->name;
             $model->file->saveAs($path);
             $result['uploadedFiles'][] = $model->file->name;
         }
         Yii::$app->response->format = Response::FORMAT_JSON;
         return $result;
     } else {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ['error' => $model->getErrors('file')];
     }
 }
 /**
  * Updates an existing Product 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);
     if ($model->load(Yii::$app->request->post())) {
         $model->image = UploadedFile::getInstance($model, 'image');
         $model->images = UploadedFile::getInstances($model, 'images');
         if ($model->validate() && $model->save()) {
             $dir = Yii::getAlias('@frontend/web/uploads/product/' . $model->id);
             if ($model->image) {
                 $model->image->saveAs($dir . '/main.jpg');
             }
             if ($model->images) {
                 $imageModels = Image::findAll(['model_id' => $model->id]);
                 if ($imageModels) {
                     foreach ($imageModels as $image) {
                         $file = $dir . '/' . $image->id . '.jpg';
                         if (file_exists($file)) {
                             unlink($file);
                         }
                         $image->delete();
                     }
                 }
                 foreach ($model->images as $image) {
                     $imageModel = new Image();
                     $imageModel->model_id = $model->id;
                     $imageModel->save();
                     $image->saveAs($dir . '/' . $imageModel->id . '.jpg');
                 }
             }
         }
         return $this->redirect(['view', 'id' => $model->id]);
     }
     return $this->render('update', ['model' => $model]);
 }
Beispiel #6
0
 /**
  * Creates a new File model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new File();
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         $dir = Yii::getAlias('@app/uf');
         foreach (UploadedFile::getInstances($model, 'files') as $file) {
             $file->saveAs($dir . '/' . $file->baseName . '.' . $file->extension);
             $new_file = new File();
             $new_file->setAttributes($model->attributes);
             $new_file->file_name = $file->baseName . '.' . $file->extension;
             $new_file->file_path = $dir . '/' . $file->baseName . '.' . $file->extension;
             $new_file->table_name = 'person';
             $new_file->class_name = Person::className();
             $new_file->save();
         }
         Yii::$app->getSession()->addFlash('success', "Запись \"{$model->id}\" успешно добавлена.");
         return $this->redirect(Url::previous() != Yii::$app->homeUrl ? Url::previous() : ['view', 'id' => $model->id]);
     } else {
         if (Yii::$app->request->referrer != Yii::$app->request->absoluteUrl) {
             Url::remember(Yii::$app->request->referrer ? Yii::$app->request->referrer : null);
         }
         if (!Yii::$app->request->isPost) {
             $model->setAttributes(Yii::$app->request->get());
         }
         return $this->render('create', ['model' => $model]);
     }
 }
Beispiel #7
0
 public function actionStudentInfo()
 {
     $user = new User();
     $model = new Student();
     $model1 = new Type();
     $region = new Region();
     $file = new UploadForm();
     //兼职的分类
     $typeInfo = $model1->getTypes();
     //获取省
     $parentOne = $region->getParentOne();
     if (Yii::$app->request->isPost) {
         $request = \YII::$app->request;
         $post = $request->post();
         $file->student_file = UploadedFile::getInstances($file, 'student_file');
         foreach ($file->student_file as $v) {
             $path = 'uploads/' . time() . rand('111', '999') . '.' . $v->extension;
             $v->saveAs($path);
             $imgUrl[] = $path;
         }
         $model->addStudent($imgUrl, $post);
     }
     $userInfo = $user->getUser(1);
     //用户信息
     return $this->render('studentinfo', ['model' => $model, 'typeInfo' => $typeInfo, 'file' => $file, 'parentOne' => $parentOne, 'userInfo' => $userInfo]);
 }
 public function actionUpload()
 {
     $model = new UploadForm();
     if (Yii::$app->request->isPost) {
         $model->file = UploadedFile::getInstances($model, 'file');
         if ($model->file && $model->validate()) {
             foreach ($model->file as $file) {
                 $model_script = new Sqlscript();
                 $save_name = '';
                 if (strtolower($file->extension) === 'txt' || strtolower($file->extension) === 'sql') {
                     $path = \Yii::getAlias('@webroot') . "/scripts/";
                     $fname = iconv('UTF-8', 'tis-620', $file->name);
                     // win
                     $save_name = $path . $fname;
                     $file->saveAs($save_name);
                     $model_script->topic = iconv('tis-620', 'UTF-8', $fname);
                     $model_script->sql_script = iconv('tis-620', 'UTF-8', file_get_contents($save_name));
                     $model_script->user = Yii::$app->user->identity->username;
                     $model_script->d_update = date('Y-m-d H:i:s');
                 }
                 $model_script->save();
             }
             return $this->redirect(['sqlscript/index']);
         }
     }
     return $this->render('upload', ['model' => $model]);
 }
 public function actionUpload()
 {
     if (Yii::$app->request->isPost) {
         $post = Yii::$app->request->post();
         $slider = Slider::findOne($post['sliderId']);
         $form = new ImageUploadForm();
         $images = UploadedFile::getInstances($form, 'images');
         foreach ($images as $k => $image) {
             $_model = new ImageUploadForm();
             $_model->image = $image;
             if ($_model->validate()) {
                 $path = \Yii::getAlias('@uploadsBasePath') . "/img/{$_model->image->baseName}.{$_model->image->extension}";
                 $_model->image->saveAs($path);
                 // Attach image to model
                 $slider->attachImage($path);
             } else {
                 foreach ($_model->getErrors('image') as $error) {
                     $slider->addError('image', $error);
                 }
             }
         }
         if ($form->hasErrors('image')) {
             $form->addError('image', count($form->getErrors('image')) . ' of ' . count($images) . ' images not uploaded');
         } else {
             Yii::$app->session->setFlash('image-success', Yii::t('app', 'Images successfully uploaded', ['Image' => Yii::t('app', 'Image'), 'images' => Yii::t('app', 'images'), 'n' => count($images)]));
         }
         return $this->redirect(['index?sliderId=' . $post['sliderId']]);
     }
 }
 /**
  * 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->shared_with = implode(',', $model->shared_with);
         $file = UploadedFile::getInstances($model, 'filename');
         foreach ($file as $filename) {
             $model1 = new Photos();
             $model1->user_id = Yii::$app->user->id;
             $model1->shared_with = $model->shared_with;
             $model1->filename = date("Ymdhis") . $filename->name;
             $path = Yii::getAlias('@uploads/albums/' . $model1->filename);
             if ($model1->save()) {
                 $filename->saveAs($path);
                 Image::thumbnail($path, 120, 120)->save(Yii::getAlias('@uploads/albums/thumbs/' . $model1->filename), ['quality' => 50]);
             }
         }
         Yii::$app->session->setFlash('success', 'Photos successfully posted.');
         Yii::$app->notification->notify($model1->filename, $model1, $model1->user, Yii::$app->controller->id, $model1->shared_with);
         $this->redirect('index');
     } else {
         if (Yii::$app->request->isAjax) {
             return $this->renderAjax('_form', ['model' => $model]);
         } else {
             return $this->render('create', ['model' => $model]);
         }
     }
 }
 /**
  * @inheritdoc
  */
 protected function load($model, $request)
 {
     if ($result = parent::load($model, $request)) {
         $model->uploadedFiles = \yii\web\UploadedFile::getInstances($model, 'uploadedFiles');
     }
     return $result;
 }
 /**
  * Updates an existing DotaPlayer 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);
     if (Yii::$app->request->isPost) {
     }
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         $model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
         //echo'<pre>';var_dump($model->imageFiles);echo'</pre>';die;
         if (count($model->imageFiles) != 0) {
             if ($model->upload()) {
                 $img_path = $model->path . '/' . $model->filename;
                 $img_dimentions = DImageHelper::getImageDimentions($img_path);
                 DImageHelper::processImage($model->path, $model->filename, 250, 250, $img_dimentions, true);
                 $model->foto = $model->filename;
             }
             $model->imageFiles = null;
         }
         //echo'<pre>';print_r($model);echo'</pre>';//die;
         if ($model->foto != $model->oldAttributes['foto'] && $model->oldAttributes['foto'] != '') {
             DFileHelper::deleteFile($model->oldAttributes['foto'], 'players');
         }
         $model->save(false);
         if (isset($_POST['save'])) {
             return $this->redirect(['index']);
         } else {
             return $this->redirect(['update', 'id' => $model->account_id]);
         }
     } else {
         //echo'<pre>';print_r($_FILES);echo'</pre>';//die;
         //echo'<pre>';print_r($model);echo'</pre>';die;
         return $this->render('update', ['model' => $model]);
     }
 }
 /**
  * Creates a new Tweet model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Tweet();
     if ($model->load(Yii::$app->request->post())) {
         $model->owner = Yii::$app->user->identity->username;
         $date = new \DateTime();
         $model->timestamp = $date->getTimestamp();
         if ($model->save()) {
             //Upload images if need be.
             $image = UploadedFile::getInstances($model, 'image');
             \Cloudinary::config(array("cloud_name" => "dxqmggd5a", "api_key" => "314154111631994", "api_secret" => "KE-AgYwX8ecm8N2omI22RDVmFv4"));
             foreach ($image as $file) {
                 $uploadResult = \Cloudinary\Uploader::upload($file->tempName);
                 $myConnection = new MediaConnections();
                 $myConnection->tweet = $model->id;
                 $myConnection->url = $uploadResult['url'];
                 $myConnection->timestamp = $model->timestamp;
                 $myConnection->save();
             }
             User::findByUsername($model->owner)->createTweet();
             return $this->redirect(Yii::$app->request->referrer);
         }
     }
     return $this->render('create', ['model' => $model]);
 }
Beispiel #14
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->generateAuthKey();
         $user->mobile = $this->mobile;
         $user->user_extra1 = $this->user_extra1;
         //上传用户信息图片, 多文件上传, 最多2张图
         $tmpStr2 = "";
         $this->files = UploadedFile::getInstances($this, 'files');
         foreach ($this->files as $file) {
             //$user->files = UploadedFile::getInstances($user, 'files');
             //foreach ($user->files as $file)
             //{
             $targetFileId = date("YmdHis") . '-' . uniqid();
             $ext = pathinfo($file->name, PATHINFO_EXTENSION);
             $targetFileName = "{$targetFileId}.{$ext}";
             $targetFile = Yii::getAlias('@webroot') . DIRECTORY_SEPARATOR . SignupForm::PHOTO_PATH . DIRECTORY_SEPARATOR . $targetFileName;
             $file->saveAs($targetFile);
             //$tmpStr2 =  $tmpStr2 . "{$targetFile};";
             $tmpStr2 = $tmpStr2 . "/user/photo/{$targetFileName};";
         }
         $user->user_extra2 = $tmpStr2;
         if ($user->save()) {
             return $user;
         }
     }
     return null;
 }
Beispiel #15
0
 public function actionView($id)
 {
     $model = tblGallery::findOne($id);
     if ($model->load($_POST)) {
         $files = \yii\web\UploadedFile::getInstances($model, 'upload_files');
         if (isset($files) && count($files) > 0) {
             $mPath = \Yii::getAlias('@webroot') . '/images/gallery/cat_' . $id;
             if (!is_dir($mPath)) {
                 mkdir($mPath);
                 chmod($mPath, '777');
             }
             foreach ($files as $file) {
                 $mPic = 'nkc_' . substr(number_format(time() * rand(), 0, '', ''), 0, 14) . '.' . $file->extension;
                 //Upload Images
                 if ($file->saveAs($mPath . '/' . $mPic)) {
                     $image = \Yii::$app->image->load($mPath . '/' . $mPic);
                     $image->resize(1024, 1024);
                     $image->save($mPath . '/' . $mPic);
                     //resize images thumb
                     $image = \Yii::$app->image->load($mPath . '/' . $mPic);
                     $image->resize(250, 250);
                     $mThumb = $mPath . '/thumb/';
                     if (!is_dir($mThumb)) {
                         mkdir($mThumb);
                         chmod($mThumb, '777');
                     }
                     $image->save($mThumb . $mPic);
                 }
             }
         }
     }
     return $this->render('view', ['model' => $model]);
 }
 /**
  * Uploads files to user's directory
  * @return string exception message if error
  * @throws GoodException if data not saved to DB
  */
 protected function uploadFiles()
 {
     try {
         $modelUpload = new UploadForm();
         $modelUpload->file = UploadedFile::getInstances($modelUpload, 'file');
         if ($modelUpload->file && $modelUpload->validate()) {
             foreach ($modelUpload->file as $file) {
                 $pathToFile = '../upload/' . Yii::$app->user->identity['login'] . '/' . $file->baseName . '.' . $file->extension;
                 if (Yii::$app->params['userWorkSpace'] - self::getUsersFilesSize('mb') < self::toMb($file->size)) {
                     throw new GoodException('Limited workspace', 'Please delete some your files for successfuly upload this file...');
                 }
                 if (!$file->saveAs($pathToFile)) {
                     throw new GoodException('Error', 'Can\'t save file...');
                 }
                 if (Files::find()->where(['path' => $file->baseName . '.' . $file->extension, 'id_user' => Yii::$app->user->identity->id])->one()) {
                     continue;
                 }
                 $modelFiles = new Files();
                 $modelFiles->id_user = Yii::$app->user->identity['id'];
                 $modelFiles->path = $file->baseName . '.' . $file->extension;
                 $modelFiles->share_link = Yii::$app->security->generateRandomString();
                 $modelFiles->size = self::toKb($file->size);
                 if (!$modelFiles->save()) {
                     unlink($pathToFile);
                     throw new GoodException('Error', 'Save data error...');
                 }
                 $this->goHome();
             }
         }
     } catch (Exception $e) {
         return $e->getMessage();
     }
 }
Beispiel #17
0
 /**
  * @return string
  */
 public function actionUploadImage()
 {
     $returnData = [];
     $className = \Yii::$app->request->get('model_name');
     $attribute = \Yii::$app->request->get('attribute');
     if ($className && $attribute) {
         $model = new $className();
         $modelName = $model->formName();
         $files = UploadedFile::getInstances($model, $attribute);
         foreach ($files as $file) {
             $originalName = $file->baseName . '.' . $file->extension;
             $fileId = FPM::transfer()->saveUploadedFile($file);
             if ($fileId) {
                 $existModelId = \Yii::$app->request->post('id');
                 $tempSign = \Yii::$app->request->post('sign');
                 $savedImage = EntityToFile::add($modelName, $existModelId, $fileId, $tempSign, \Yii::$app->request->get('entity_attribute'));
                 if (!$savedImage) {
                     $returnData['error'][] = 'Не получилось связать файл ' . $originalName . ' с моделью';
                 } else {
                     $returnData = ['deleteUrl' => ImagesUploadModel::deleteImageUrl(['id' => $savedImage->id]), 'cropUrl' => ImagesUploadModel::getCropUrl(['id' => $savedImage->id]), 'id' => $savedImage->id, 'imgId' => $savedImage->file_id];
                 }
             } else {
                 $returnData['error'][] = 'Не получилось сохранить файл ' . $originalName;
             }
         }
     }
     return Json::encode($returnData);
 }
 public function actionUpload()
 {
     $model = new UploadForm();
     $model->file = UploadedFile::getInstances($model, 'file');
     if ($model->rules()[0]['maxFiles'] == 1) {
         $model->file = UploadedFile::getInstances($model, 'file')[0];
     }
     if ($model->file && $model->validate()) {
         $result['uploadedFiles'] = [];
         if (is_array($model->file)) {
             foreach ($model->file as $file) {
                 /** @var UploadedFile $file */
                 $path = $this->getModule()->getUserDirPath() . DIRECTORY_SEPARATOR . $file->name;
                 $file->saveAs($path);
                 $result['uploadedFiles'][] = $file->name;
             }
         } else {
             $path = $this->getModule()->getUserDirPath() . DIRECTORY_SEPARATOR . $model->file->name;
             $model->file->saveAs($path);
         }
         return json_encode($result);
     } else {
         return json_encode(['error' => $model->errors['file']]);
     }
 }
Beispiel #19
0
 public static function uploadFiles($model)
 {
     // get the uploaded file instance. for multiple file uploads
     // the following data will return an array (you may need to use
     // getInstances method)
     $attachments = UploadedFile::getInstances($model, 'attachment');
     //var_dump($images); exit;
     // if no image was uploaded abort the upload
     if (empty($attachments)) {
         $model->attachment = '';
         return false;
     }
     $attachments_array = array();
     foreach ($attachments as $attachment) {
         // store the source file name
         $filename = explode(".", $attachment->name);
         $ext = end($filename);
         // generate a unique file name
         $name = str_replace(".{$ext}", '', $attachment->name) . '_' . time() . ".{$ext}";
         $attachments_array[] = $name;
         $attachment->name = $name;
     }
     // the uploaded image instance
     $model->attachment = Json::encode($attachments_array);
     return $attachments;
 }
Beispiel #20
0
 /**
  * Lists all Images models.
  * @return mixed
  */
 public function actionIndex($itemId)
 {
     if (!Product::find()->where(['item_id' => $itemId])->exists()) {
         throw new NotFoundHttpException();
     }
     $form = new MultipleUploadForm();
     $searchModel = new ImagesSearch();
     $searchModel->item_id = $itemId;
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
     if (Yii::$app->request->isPost) {
         $form->files = UploadedFile::getInstances($form, 'files');
         if ($form->files && $form->validate()) {
             foreach ($form->files as $file) {
                 $images = new Images();
                 $images->item_id = $itemId;
                 if ($images->save()) {
                     // writes file name to images table
                     $images->big_image = $images->getUrl();
                 }
                 if ($images->save()) {
                     // saves file to folder
                     $file->saveAs($images->getPath());
                 }
             }
         }
     }
     return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'uploadForm' => $form]);
 }
 /**
  * Updates an existing lab model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $lab = lab::find()->where(['id' => $id])->one();
     $lab_ru = lab_ru::find()->where(['lab_id' => $id])->one();
     $lab_en = lab_en::find()->where(['lab_id' => $id])->one();
     if (!empty(UploadedFile::getInstances($lab, 'images'))) {
         if ($lab->load(Yii::$app->request->post())) {
             if (file_exists($path = getcwd() . '\\..\\..' . $lab->photo_path)) {
                 unlink($path);
             }
             if (file_exists($path = getcwd() . '\\..\\..' . $lab->photo_path427320)) {
                 unlink($path);
             }
             $images = UploadedFile::getInstances($lab, 'images');
             $newFileName = date("YmdHis");
             $filePath = Yii::getAlias('@frontend') . '/web/uploads/' . $newFileName . '.' . $images[0]->extension;
             $file427320 = Yii::getAlias('@frontend') . '/web/uploads/427320/' . $newFileName . '.' . $images[0]->extension;
             $images[0]->saveAs($filePath);
             Image::thumbnail($filePath, 427, 320)->save($file427320, ['quality' => 50]);
             $lab->photo_path = Yii::getAlias('@resource') . '/uploads/' . $newFileName . '.' . $images[0]->extension;
             $lab->photo_path427320 = Yii::getAlias('@resource') . '/uploads/427320/' . $newFileName . '.' . $images[0]->extension;
         }
     }
     if ($lab->load(Yii::$app->request->post()) && $lab_ru->load(Yii::$app->request->post()) && $lab_en->load(Yii::$app->request->post()) && $lab->save()) {
         $lab_ru->save();
         $lab_en->save();
         return $this->redirect(['update', 'id' => $lab->id]);
     } else {
         return $this->render('update', ['lab' => $lab, 'lab_ru' => $lab_ru, 'lab_en' => $lab_en]);
     }
 }
 public function actionUpload()
 {
     // @todo Update code
     // http://webtips.krajee.com/ajax-based-file-uploads-using-fileinput-plugin/
     if (Yii::$app->request->isPost) {
         $post = Yii::$app->request->post();
         $gallery = Gallery::findOne(Yii::$app->session->get('gallery.gallery-id'));
         $form = new ImageUploadForm();
         $images = UploadedFile::getInstances($form, 'images');
         foreach ($images as $k => $image) {
             $_model = new ImageUploadForm();
             $_model->image = $image;
             if ($_model->validate()) {
                 $path = \Yii::getAlias('@uploadsBasePath') . "/img/{$_model->image->baseName}.{$_model->image->extension}";
                 $_model->image->saveAs($path);
                 // Attach image to model
                 $gallery->attachImage($path);
             } else {
                 foreach ($_model->getErrors('image') as $error) {
                     $gallery->addError('image', $error);
                 }
             }
         }
         if ($form->hasErrors('image')) {
             // @todo Translate
             $response['message'] = count($form->getErrors('image')) . ' of ' . count($images) . ' images not uploaded';
         } else {
             $response['message'] = Yii::t('app', '{n, plural, =1{Image} other{# images}} successfully uploaded', ['n' => count($images)]);
         }
         Yii::$app->response->format = Response::FORMAT_JSON;
         return $response;
     }
 }
Beispiel #23
0
 /**
  * Creates a new UrQuestions model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new UrQuestions();
     $model->user_id = \Yii::$app->user->identity->id;
     $UrRecords = Ur::find()->orderBy('name');
     if (\Yii::$app->user->identity->status == 2) {
         $UrRecords = $UrRecords->Where(['regional_id' => \Yii::$app->user->identity->id]);
     }
     if (\Yii::$app->user->identity->status == 3) {
         //    $UrRecords = $UrRecords->Where(['pi_id' => \Yii::$app->user->identity->id]);
     }
     $UrRecords = $UrRecords->all();
     //->where(['pi_id' => $user])
     if (Yii::$app->request->isPost) {
         // print_r($model->qfile);
         $model->qfile = UploadedFile::getInstances($model, 'qfile');
         if (!empty($model->qfile)) {
             $model->qfiles = "";
             foreach ($model->qfile as $file) {
                 $fileName = 'files/qfile/' . Functions::str2url($file->baseName) . rand(555, 99999) . '.' . $file->extension;
                 $model->qfiles .= $fileName . "|";
                 $file->saveAs($fileName);
             }
             $model->qfiles = substr($model->qfiles, 0, -1);
         }
     }
     if ($model->load(Yii::$app->request->post()) && ($id = $model->save())) {
         $info = UrQuestions::getInfo($model->id);
         Word::ur_questions($info);
         return $this->redirect(['index']);
     } else {
         return $this->render('create', ['model' => $model, 'UrRecords' => $UrRecords]);
     }
 }
 /**
  * @return string
  */
 public function actionIndex()
 {
     $advertisement = new Advertisement();
     $advertisement->load(Yii::$app->request->post());
     $advertisement->id_user = Yii::$app->getUser()->id;
     $advertisement->file = UploadedFile::getInstances($advertisement, 'file');
     $fileNames = [];
     if ($advertisement->file && $advertisement->validate()) {
         foreach ($advertisement->file as $file) {
             $fileName = md5(uniqid(rand(), 1));
             $fileNames[] = [$fileName];
             $file->saveAs('uploads/' . $fileName . '.' . $file->extension);
         }
         try {
             $advertisement->save();
         } catch (Exception $e) {
             return $e->getMessage();
         }
         foreach ($fileNames as $key => $value) {
             $value[] = 0;
             $value[] = $advertisement->id;
             $fileNames[$key] = $value;
         }
         try {
             Yii::$app->db->createCommand()->batchInsert(ImageAdvertisement::tableName(), ['path', 'is_logo', 'id_advertising'], $fileNames)->execute();
             $this->redirect(['update', 'id' => $advertisement->id]);
         } catch (Exception $e) {
             return $e->getMessage();
         }
     }
     return $this->render('index', ['model' => $advertisement]);
 }
Beispiel #25
0
 public function attachImages($event)
 {
     $model = $event->sender;
     $images = UploadedFile::getInstances($model, 'imagesUpload');
     foreach ($images as $image) {
         $model->attachImage($image);
     }
 }
Beispiel #26
0
 /**
  * Multiple image upload
  *
  * @param null $dir
  */
 public function uploadImages($dir = null)
 {
     // Upload multiple images
     $this->owner->images = \yii\web\UploadedFile::getInstances($this->owner, 'images');
     foreach ($this->owner->images as $image) {
         $this->uploadImage($dir, $image);
     }
 }
Beispiel #27
0
 protected function createAndSaveUploadedMedias($attribute)
 {
     $class = $this->fileModelClass;
     $uploadedMedias = UploadedFile::getInstances($this->owner, $attribute);
     foreach ($uploadedMedias as $uploadedFile) {
         $class::makeByUploadedFile($uploadedFile, $this->owner, $attribute);
     }
 }
Beispiel #28
0
 /**
  * Lists all Image models.
  * @param int $id product id
  * @return mixed
  *
  * @throws NotFoundHttpException
  */
 public function actionIndex($id)
 {
     $form = new MultipleUploadForm();
     if (!Product::find()->where(['id' => $id])->exists()) {
         throw new NotFoundHttpException();
     }
     $searchModel = new ImageSearch();
     $searchModel->product_id = $id;
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
     if (Yii::$app->request->isPost) {
         $form->files = UploadedFile::getInstances($form, 'files');
         if ($form->files && $form->validate()) {
             foreach ($form->files as $file) {
                 //
                 // UPLOADING THE IMAGE:
                 //
                 $image = new Image();
                 $image->product_id = $id;
                 if ($image->save()) {
                     // Save an original image;
                     $path = $image->getPath();
                     $file->saveAs($path);
                     // Original size:
                     $size = getimagesize($path);
                     $height = $size[1];
                     $width = $size[0];
                     // IMAGINE
                     ImagineImage::$driver = [ImagineImage::DRIVER_GD2];
                     $imagine = new Imagine();
                     $picture = $imagine->open($path);
                     //---------------------------
                     //                        $size = new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT);
                     //                        $center = new Center($size);
                     //---------------------------
                     //                        $picture->crop(new Point(0, 0),
                     //                            new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT))->save($path);
                     /**
                      * If the image's height is bigger than needed, it must be cut.
                      * Otherwise it must be resized.
                      */
                     if ($height >= self::IMAGE_HEIGHT) {
                         $picture->thumbnail(new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT))->save($path, ['quality' => 100]);
                         // re-save cropped image;
                     } else {
                         $picture->resize(new Box(self::IMAGE_WIDTH, self::IMAGE_HEIGHT))->save($path);
                     }
                     sleep(1);
                     //                        $background = new Color('#FFF');
                     //                        $topLeft    = new Point(0, 0);
                     //                        $canvas = $imagine->create(new Box(450, 450), $background);
                     //                        $canvas->paste($picture, $topLeft)->save($path);
                 }
             }
         }
     }
     return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'uploadForm' => $form]);
 }
 public function actionUpload()
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     $result = [];
     $files = UploadedFile::getInstances(new File(), 'uploadedFiles');
     foreach ($files as $index => $file) {
         $model = new File();
         $model->uploadedFiles = [$file];
         $model->user_id = Yii::$app->user->id;
         $model->storage = File::STORAGE_OS;
         $model->extension = $file->extension;
         $model->type = File::defineType($model->extension);
         if ($model->upload()) {
             $item = ['id' => $model->id, 'url' => $model->getUrl(), 'type' => $model->getMimeType()];
             if ($releaseId = Yii::$app->request->get('rid')) {
                 $release = Release::findOne($releaseId);
                 if ($release && $release->artist->user_id == Yii::$app->user->id) {
                     if ($model->type == $model::TYPE_IMAGE) {
                         $cover = new Cover(['release_id' => $release->id, 'file_id' => $model->id, 'is_main' => false]);
                         $cover->save();
                         $item['image_id'] = $cover->id;
                     } elseif ($model->type == $model::TYPE_AUDIO) {
                         $track = new Track(['release_id' => $release->id, 'original_name' => $file->baseName, 'number' => $release->getTracks()->count() + 1, 'file_id' => $model->id]);
                         $track->save();
                         $item['track_id'] = $track->id;
                         $item['comname'] = $track->getComname();
                         $item['number'] = $track->number;
                     }
                 }
             }
             if ($artistId = Yii::$app->request->get('aid')) {
                 $photo = new Photo(['artist_id' => (string) $artistId, 'file_id' => $model->id, 'is_main' => false]);
                 $artist = Artist::findOne($artistId);
                 if ($artist && $artist->user_id == Yii::$app->user->id) {
                     $photo->save();
                     $item['image_id'] = $photo->id;
                 }
             }
             //                if ($model->type == $model::TYPE_AUDIO) {
             //                    $getID3 = new getID3();
             //                    $tags = $getID3->analyze($model->getPath(true))['tags']['id3v2'];
             //                    $item['meta'] = [
             //                        'title' => $tags['title'][0],
             //                        'number' => explode('/', $tags['track_number'][0])[0],
             //                        'disc' => explode('/', $tags['part_of_a_set'][0])[0],
             //                        'lyric' => $tags['unsynchronised_lyric'][0],
             //                        'info' => $tags['comment'][0],
             //                    ];
             //                }
             if ($model->type == $model::TYPE_AUDIO) {
                 $item['meta'] = ['title' => $file->baseName, 'number' => $index + 1, 'disc' => '', 'lyric' => '', 'info' => ''];
             }
             $result[] = $item;
         }
     }
     return $result;
 }
Beispiel #30
0
 /**
  * @param Model $model
  * @param array $attributes
  * @param bool  $multiple
  */
 public function prepare($model, $attributes, $multiple = null)
 {
     if ($model !== null && $attributes !== null) {
         if (is_array($attributes)) {
             $this->model = $model;
             $this->attributes = $attributes;
             foreach ($attributes as $attribute) {
                 $_files = $this->UploadedFile->getInstances($model, $attribute);
                 if (!$multiple) {
                     $_files ? $this->model->{$attribute} = $_files[0] : null;
                 } else {
                     $this->model->{$attribute} = $_files;
                 }
             }
         } else {
             $this->prepare($model, [$attributes], $multiple);
         }
     }
 }