Example #1
0
 public function actionSaveTemplate()
 {
     $request = Yii::$app->request;
     if ($request->isPost) {
         $model_upload = new UploadForm();
         $model_upload->file = UploadedFile::getInstanceByName('DocContent');
         if ($model_upload->validate()) {
             $id = $request->get("id");
             $model = DocumentTemplate::find()->where(["DocumentID" => $id])->one();
             if (!$model) {
                 $model = new DocumentTemplate();
             }
             $model->DocumentID = $id;
             $model->URL = "/uploads/print/template/test.doc";
             $model->save();
             $model->URL = "/uploads/print/template/" . $model->ID . ".doc";
             $model->save();
             $path = dirname(Yii::$app->basePath) . $model->URL;
             if ($model_upload->file->saveAs($path)) {
                 echo "success";
                 exit;
             }
         } else {
             echo "failed";
         }
     }
 }
Example #2
0
 public function actionUpload()
 {
     return $this->goHome();
     $model = new UploadForm();
     if ($model->load(Yii::$app->request->post())) {
         // get the uploaded file instance. for multiple file uploads
         // the following data will return an array
         $image = UploadedFile::getInstance($model, 'image');
         // store the source file name
         $filename = $image->name;
         //    echo $filename; exit;
         //   $ext = end((explode(".", $image)));
         // generate a unique file name
         // $avatar = Yii::$app->security->generateRandomString().".{$ext}";
         // the path to save file, you can set an uploadPath
         // in Yii::$app->params (as used in example below)
         $path = Yii::$app->params['uploadPath'] . $filename;
         //    if($model->validate()){
         //    $image->saveAs($path);
         $image->saveAs('../uploads/' . $filename);
         return $this->redirect(['upload']);
         //  } else {
         // error in saving model
         //    }
     }
     return $this->render('upload', ['model' => $model]);
 }
Example #3
0
 public function actionUpload($id)
 {
     $picture = new UploadForm();
     //$picture->tour_id = $id;
     $picture->image = UploadedFile::getInstancesByName('attachment_' . $id . '');
     //echo '<pre> File2: ' . print_r( $picture->image, TRUE). '</pre>'; die();
     $picture->id = $id;
     $picture->saveImages();
     return $this->redirect(Yii::$app->request->referrer);
 }
 public function actionIndex()
 {
     // 'cos I can't install mcrypt on ma-webproxy-04 right now
     //Yii::$app->request->enableCsrfValidation = false;
     $model = new UploadForm();
     if (empty(Yii::$app->params['uploadPath'])) {
         Yii::$app->session->setFlash('error', 'Please configure the upload path');
     } elseif ($model->load(Yii::$app->request->post())) {
         return $this->loadImages($model);
     }
     return $this->render('index', ['model' => $model]);
 }
Example #5
0
 public function actionUpload($documentID = null)
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     $result = ['success' => false];
     $uploadForm = new UploadForm();
     $uploadForm->file = UploadedFile::getInstanceByName('file');
     $uploadForm->documentID = $documentID;
     if ($uploadForm->validate() && $uploadForm->upload()) {
         $result['success'] = true;
     }
     return $result;
 }
 /**
  * Creates a new Books model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Books();
     $upload = new UploadForm();
     $upload->imageFile = UploadedFile::getInstance($model, 'img');
     if ($upload->upload()) {
         $model->status = 'available';
         if ($model->load(Yii::$app->request->post())) {
             $model->img = 'images/' . $upload->imageFile->baseName . '.' . $upload->imageFile->extension;
             if ($model->save()) {
                 return $this->redirect(['view', 'id' => $model->id]);
             }
         }
     }
     return $this->render('create', ['model' => $model]);
 }
Example #7
0
 public function actionUpload()
 {
     $model = new UploadForm();
     $username = Yii::$app->session['username'];
     $user = User::find()->where(['username' => $username])->one();
     if (Yii::$app->request->isPost) {
         $model->file = UploadedFile::getInstanceByName('file');
         $name = time();
         $url = Yii::$app->basePath . "/web" . '/';
         if ($model->validate()) {
             $model->file->saveAs($url . 'images/' . $name . '.' . $model->file->extension);
             $user->facepic = "images/" . $name . '.' . $model->file->extension;
             $user->save();
         }
     }
     echo "1";
 }
 public function create(string $boardName, array $data)
 {
     /** @var Board $board */
     if (!($board = Board::findOne(['name' => $boardName]))) {
         throw new UserException('Board was not found', 404);
     }
     $validationParams = $board->postsSettings->getValidationParams();
     $thread = new Thread(['boardId' => $board->id]);
     $postData = new PostData(['validationParams' => $validationParams]);
     $uploadForm = new UploadForm(['files' => PostedFile::getPostedFiles($validationParams['maxFiles']), 'validationParams' => $validationParams]);
     $toLoad = [$thread, $postData];
     $toValidate = [$thread, $postData, $uploadForm];
     if (!ARExtended::loadMultiple($toLoad, $data) || !Model::validateMultiple($toValidate)) {
         throw new UserException('Failed to load/validate data', 400);
     }
     if (strlen($postData->messageText) == 0 && count($uploadForm->files)) {
         throw new UserException('Must be attached atleast 1 file or non-empty message', 400);
     }
     $toSave = [$postData, $thread, $uploadForm];
     $postData->on(PostData::EVENT_AFTER_INSERT, function ($event) use($thread) {
         $thread->postDataId = $event->sender->id;
     });
     $saved = true;
     foreach ($toSave as $model) {
         if (method_exists($model, 'save')) {
             $saved = $saved && $model->save();
             if (!$saved) {
                 break;
             }
         }
     }
     if (!$saved) {
         for ($i = count($toSave) - 1; $i >= 0; $i--) {
             method_exists($toSave[$i], 'delete') && $toSave[$i]->delete();
         }
         throw new UserException('Failed to create thread', 500);
     }
     foreach ($uploadForm->getFileInfos() as $fileInfo) {
         $postData->link('fileInfos', $fileInfo);
     }
     $thread->link('board', $board);
     return $thread;
 }
Example #9
0
 public function actionEdit()
 {
     $request = Yii::$app->request;
     if (Yii::$app->request->isPost) {
         $model_upload = new UploadForm();
         //var_dump($_FILES);
         $model_upload->file = UploadedFile::getInstanceByName('DocContent');
         if ($model_upload->validate()) {
             $model = Report::find()->where(["ID" => $request->get("id")])->one();
             $path = "/uploads/report/" . $model->Type . "/" . $model->UID;
             $filename = dirname(Yii::getAlias('@app')) . $path . "/" . $model->ID . '.' . $model_upload->file->extension;
             if ($model_upload->file->saveAs($filename)) {
                 echo "success";
                 exit;
             }
         }
     }
     echo "failed";
 }
 public function actionProfileImageUpload($user_id = null)
 {
     $result = 0;
     if (Yii::$app->request->isPost) {
         $profileModel = $this->finder->findProfileById($user_id);
         if ($profileModel != null && $profileModel->user_id == Yii::$app->user->identity->getId()) {
             $uploadForm = new UploadForm();
             $uploadForm->addSegments(['user', $user_id]);
             $uploadForm->imageFile = UploadedFile::getInstance($uploadForm, 'imageFile');
             if ($uploadForm->upload()) {
                 $profileModel->image_url = $uploadForm->uploadedUrl();
                 if ($profileModel->save()) {
                     $result = 1;
                 }
             }
         }
     }
     \Yii::$app->response->format = Response::FORMAT_JSON;
     \Yii::$app->response->data = ['result' => $result, 'image_url' => $result ? $profileModel->image_url : ''];
     \Yii::$app->end();
 }
Example #11
0
 /**
  * Отвечает за загрузку изображений из формы редактирования записи
  * @return javascript string
  * @throws NotFoundHttpException if the model cannot be found
  */
 function actionUpload()
 {
     //return  ("<script>top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('/uploads/555efba5c24a7.jpg').closest('.mce-window').find('.mce-primary').click();</script>" );
     $upload_model = new UploadForm();
     $upload_model->load(yii::$app->request->post());
     $file = UploadedFile::getInstance($upload_model, 'file');
     if ($file->error === UPLOAD_ERR_OK) {
         try {
             $file_model = new Files();
             $file_model->saveImageFile($file);
             $file_model->post_id = $upload_model->post_id;
             $file_model->save();
             return "<script>top.\$('.mce-btn.mce-open').parent().find('.mce-textbox').val('/{$file_model->filename}').closest('.mce-window').find('.mce-primary').click();</script>";
         } catch (\Exception $e) {
         }
     }
     return "<script>\$.jGrowl('ошибка, файл не получен');</script>";
 }
Example #12
0
 public function actionUpdateProfile()
 {
     if (!Yii::$app->user->isGuest) {
         if (Yii::$app->request->get('new')) {
             $model = new Profile();
             $avatar = "";
             $user_id = Yii::$app->user->id;
         } else {
             if (Yii::$app->request->get('id')) {
                 $user_id = Yii::$app->request->get('id');
             } else {
                 $user_id = Yii::$app->user->id;
             }
             $model = Profile::find()->where(['user_id' => $user_id])->one();
             if (!empty($model->avatar)) {
                 $avatar = $model->avatar;
             }
         }
         if (Yii::$app->request->post()) {
             $model->user_id = $user_id;
             $model->first_name = Yii::$app->request->post('Profile')['first_name'];
             $model->second_name = Yii::$app->request->post('Profile')['second_name'];
             $model->last_name = Yii::$app->request->post('Profile')['last_name'];
             $model->birthday = Yii::$app->request->post('Profile')['birthday'];
             $model->about = Yii::$app->request->post('Profile')['about'];
             $model->location = Yii::$app->request->post('Profile')['location'];
             $model->sex = Yii::$app->request->post('Profile')['sex'];
             $upload = new UploadForm();
             if ($upload->imageFiles = UploadedFile::getInstances($model, 'avatar')) {
                 if (!empty($avatar)) {
                     if (file_exists(Yii::getAlias('@webroot/uploads/image_profile/original/' . $avatar))) {
                         unlink(Yii::getAlias('@webroot/uploads/image_profile/original/' . $avatar));
                         unlink(Yii::getAlias('@webroot/uploads/image_profile/xm/' . $avatar));
                         unlink(Yii::getAlias('@webroot/uploads/image_profile/sm/' . $avatar));
                         unlink(Yii::getAlias('@webroot/uploads/image_profile/lm/' . $avatar));
                     }
                 }
                 $filename = $upload->upload('image_profile/');
                 $model->avatar = $filename[0] . '.' . $upload->imageFiles[0]->extension;
             } else {
                 $model->avatar = $avatar;
             }
             if ($model->save()) {
                 Yii::$app->session->setFlash('success', "Профиль изменен");
                 return $this->redirect(['/user/view-profile', 'id' => $user_id]);
             } else {
                 Yii::$app->session->setFlash('error', "Не удалось изменить профиль");
                 Yii::error('Ошибка записи. Профиль не изменен');
                 return $this->refresh();
             }
         } else {
             return $this->render('update-profile', ['model' => $model]);
         }
     } else {
         Yii::$app->session->setFlash('error', 'Нет доступа!');
         return $this->redirect('/');
     }
 }
Example #13
0
 public function actionUpdate($id)
 {
     if (!Yii::$app->user->can('product/update')) {
         Yii::$app->session->setFlash('error', 'Нет доступа!');
         return $this->redirect('/');
     }
     $categories = Product::loadCategory();
     $model = $this->findModel($id);
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         Images::deleteImages($model);
         $upload = new UploadForm();
         $upload->imageFiles = UploadedFile::getInstances($model, 'images');
         if ($filename = $upload->upload('image_product/')) {
             Images::loadImages($upload, $filename, $model->id);
         }
         $model->sizeImages();
         return $this->redirect(['view', 'id' => $model->id]);
     } else {
         return $this->render('update', ['model' => $model, 'categories' => $categories]);
     }
 }
Example #14
0
    public function actionImport()
    {
        $model = new UploadForm();
        $request = Yii::$app->request;
        $arr = [];
        if ($request->isPost) {
            $model->file = UploadedFile::getInstanceByName('file');
            if ($model->validate()) {
                $path = dirname(Yii::getAlias('@app')) . '/uploads/' . $this->depart_id . 'import.' . $model->file->extension;
                $model->file->saveAs($path);
                error_reporting(E_ALL);
                date_default_timezone_set('Asia/shanghai');
                $objPHPExcel = new \PHPExcel();
                $objReader = \PHPExcel_IOFactory::createReaderForFile($path);
                $objPHPExcel = $objReader->load($path);
                $objPHPExcel->setActiveSheetIndex(0);
                $objWorksheet = $objPHPExcel->getActiveSheet();
                $i = 0;
                foreach ($objWorksheet->getRowIterator() as $row) {
                    $cellIterator = $row->getCellIterator();
                    $cellIterator->setIterateOnlyExistingCells(false);
                    foreach ($cellIterator as $cell) {
                        $value = $cell->getFormattedValue();
                        $arr[$i][] = $value;
                    }
                    $i++;
                }
            }
        }
        $script = <<<JS
        \$("#pop .pop-title", window.parent.document).html("{$this->_model->type}导入");
        \$("#footer").append('<input type="button" name="delColSelected" value="删除选定列">   | ');
        \$("#footer").append('<input type="button" name="delRowSelected" value="删除选定行">  | ');
        \$("#footer").append('<input type="button" name="cleanColSelected" value="清除选定列">  | ');
        \$("#footer").append('<input type="text" name="ACol" size="3">O<input type="text" name="BCol" size="3"><input type="button" name="DH" value="倒换"> |');
        \$("#footer").append('<input type="text" id="yy" size="4"><input type="button" name="setYear" value="设置年份"> |');
JS;
        $this->layout = "edit";
        return $this->render("import", ["model" => $this->_model, "script" => $script, "excel" => $arr, "action" => $request->get("action")]);
    }
Example #15
0
 protected function isUploaded($model)
 {
     $up = new UploadForm();
     $up->cover = UploadedFile::getInstance($model, 'cover');
     $up->carousel = UploadedFile::getInstances($model, 'carousel');
     if ($this->source = $up->upload()) {
         $arr = $this->source;
         $model->cover = $arr['0'];
         $model->one = $arr['1'];
         $model->two = $arr['2'];
         $model->three = $arr['3'];
         $model->four = $arr['4'];
         $model->five = $arr['5'];
         // 封面图片处理,有首页大图小图,期刊页列表图缩略图
         $big = Yii::getAlias('@app') . '/uploads/big' . pathinfo($arr['0'])['basename'];
         $small = Yii::getAlias('@app') . '/uploads/small' . pathinfo($arr['0'])['basename'];
         $list = Yii::getAlias('@app') . '/uploads/list' . pathinfo($arr['0'])['basename'];
         $thumb = Yii::getAlias('@app') . '/uploads/thumb' . pathinfo($arr['0'])['basename'];
         Image::thumbnail($arr['0'], 640, 426)->save($big, ['quality' => 80]);
         Image::thumbnail($arr['0'], 303, 202)->save($small, ['quality' => 80]);
         Image::thumbnail($arr['0'], 540, 393)->save($list, ['quality' => 80]);
         Image::thumbnail($arr['0'], 46, 30)->save($thumb, ['quality' => 80]);
     }
     if ($model->save()) {
         return $this->redirect(['view', 'id' => $model->id]);
     }
 }
Example #16
0
 /**
  * 编辑资料页面
  * If update is successful, the browser will be redirected to the 'view' page.
  *
  * @param integer $id            
  * @return mixed
  */
 public function actionEdit()
 {
     $model = $this->findModel(Yii::$app->user->identity->getId());
     if (Yii::$app->request->isPost) {
         $post = Yii::$app->request->post();
         $up = new UploadForm();
         $up->photo = UploadedFile::getInstance($model, 'photo');
         if ($up->photo) {
             $path = $up->upload($model->id);
             $post['User']['photo'] = $path;
         } else {
             $post['User']['photo'] = $model->photo;
         }
         if ($model->load($post) && $model->save()) {
             return $this->redirect(['edit']);
         }
     } else {
         return $this->render('update', ['model' => $model]);
     }
 }
 public function actionUpload()
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     $document = $this->findModel(Yii::$app->request->post('id'));
     $model = new UploadForm();
     if (Yii::$app->request->isAjax) {
         $model->files = UploadedFile::getInstancesByName('files');
         $model->document_id = $document->id;
         if ($model->upload()) {
             return ['fileuploaded' => 'true'];
         } else {
             return $model->errors;
         }
     }
 }
 public function actionUpload($key = null)
 {
     $readyPicsCount = Picture::find()->where(['state' => 'ready'])->count();
     $lastPictures = Picture::find()->where(['state' => 'ready'])->orderBy('updated ASC')->limit(50)->offset($readyPicsCount - 50)->all();
     $avgPictureTime = 0;
     if (count($lastPictures) > 1) {
         $summ = 0;
         for ($i = 1; $i < count($lastPictures); $i++) {
             $diff = strtotime($lastPictures[$i]->updated) - strtotime($lastPictures[$i - 1]->updated);
             $summ += $diff;
         }
         $avgPictureTime = intval($summ / (count($lastPictures) - 1));
     }
     $readyTime = $avgPictureTime * Picture::find()->where(['state' => 'new'])->count();
     $myPictureDP = new ActiveDataProvider(['query' => Picture::find()->where(['state' => 'new', 'ip' => Yii::$app->getRequest()->getUserIP()]), 'sort' => false]);
     $lastPending = Picture::find()->where(['state' => 'pending'])->orderBy('id DESC')->one();
     if ($lastPending == null) {
         $lastPending = Picture::find()->where(['state' => 'ready'])->orderBy('id DESC')->one();
     }
     $pendingPicsCount = Picture::find()->where(['state' => 'new'])->count();
     $algorithms = [];
     $algos = Algorithm::find()->orderBy('count DESC')->all();
     foreach ($algos as $algo) {
         if (count($algorithms) == 0) {
             $algorithms[$algo->getPrimaryKey()] = $algo->name . ' (default, ' . $algo->count . ' pics)';
         } else {
             $algorithms[$algo->getPrimaryKey()] = $algo->name . ' (' . $algo->count . ' pics)';
         }
     }
     $viewData = ['readyTime' => $readyTime, 'myPictureDP' => $myPictureDP, 'avgPictureTime' => $avgPictureTime, 'lastPendingId' => $lastPending->id, 'pendingPicsCount' => $pendingPicsCount, 'algorithms' => $algorithms, 'algos' => $algos];
     $priority = 0;
     if ($key != null) {
         $keyModel = Key::find()->where(['value' => $key])->andWhere('used < count')->one();
         if ($keyModel == null) {
             throw new HttpException(404, "Bad key");
         }
         $priority = $keyModel->priority;
         $viewData['key'] = $keyModel;
     }
     $model = new UploadForm();
     if ($model->load(Yii::$app->request->post())) {
         $image = UploadedFile::getInstance($model, 'image');
         $model->image = $image;
         if ($model->validate() && $model->check()) {
             $size = getimagesize($image->tempName);
             list($width, $height, $type) = $size;
             if ($type == IMAGETYPE_JPEG) {
                 $img = imagecreatefromjpeg($image->tempName);
             } else {
                 if ($type == IMAGETYPE_PNG) {
                     $img = imagecreatefrompng($image->tempName);
                 } else {
                     throw new HttpException(400, 'Bad image');
                 }
             }
             $srcName = Helper::gen_uuid() . '.jpg';
             $filename = \Yii::$app->basePath . '/web/images/' . $srcName;
             $k = 650;
             if (!($width <= $k && $height <= $k)) {
                 $minSide = (int) (min($width, $height) * $k / max($width, $height));
                 list($newWidth, $newHeight) = $width > $height ? [$k, $minSide] : [$minSide, $k];
                 $newImage = imagecreatetruecolor($newWidth, $newHeight);
                 imagecopyresampled($newImage, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                 imagejpeg($newImage, $filename, 100);
             } else {
                 imagejpeg($img, $filename, 100);
             }
             $hash = sha1(file_get_contents($filename));
             $count = Picture::find()->where(['hash' => $hash, 'algorithmId' => $model->algoId])->all();
             if (count($count) > 0) {
                 unlink($filename);
                 $first = $count[0];
                 Yii::$app->getSession()->setFlash('success', 'This image was already submitted.');
                 return $this->redirect('/picture/' . $first->getPrimaryKey());
             }
             $algo = Algorithm::find()->where(['id' => $model->algoId])->one();
             $picture = new Picture();
             $picture->email = $model->email;
             $picture->ip = \Yii::$app->getRequest()->getUserIP();
             $picture->source = $srcName;
             $picture->output = null;
             $picture->state = 'new';
             $picture->hash = $hash;
             $picture->status = 0;
             $picture->priority = $priority;
             $picture->algorithm = $algo->name;
             $picture->algorithmId = $model->algoId;
             $picture->save();
             $algo->count += 1;
             $algo->save();
             if (!empty($keyModel)) {
                 $keyModel->used += 1;
                 $keyModel->save();
                 \Yii::$app->getSession()->setFlash('success', 'Your image were successfully uploaded. Converted image will be ready <b>ASAP</b> and sent on your email. Thank you!');
             } else {
                 \Yii::$app->getSession()->setFlash('success', 'Your image were successfully uploaded. Converted image will be ready after ~' . Helper::formatHourAndMin($readyTime) . ' and sent on your email. Thank you!');
             }
             return $this->redirect('/picture/' . $picture->getPrimaryKey());
         }
     }
     $viewData['model'] = $model;
     return $this->render('upload', $viewData);
 }
Example #19
0
 protected function isUploaded($model)
 {
     $up = new UploadForm();
     $up->scenario = 'productUpload';
     $up->front = UploadedFile::getInstance($model, 'front');
     $up->back = UploadedFile::getInstance($model, 'back');
     if ($this->source = $up->productUpload()) {
         $arr = $this->source;
         $model->front = '/uoploads/' . basename($arr['0']);
         $model->back = '/uoploads/' . basename($arr['1']);
         // 封面图片处理,正面反面
         $frontName = Yii::getAlias('@app') . '/uploads/' . pathinfo($arr['0'])['basename'];
         $backName = Yii::getAlias('@app') . '/uploads/' . pathinfo($arr['1'])['basename'];
         Image::thumbnail($arr['0'], 240, 240)->save($frontName, ['quality' => 80]);
         Image::thumbnail($arr['1'], 240, 240)->save($backName, ['quality' => 80]);
         if ($model->save()) {
             return $this->redirect(['view', 'id' => $model->id]);
         }
     }
 }
Example #20
0
 public function actionUploadcsv()
 {
     $model = new UploadForm();
     //        if (Yii::$app->request->isPost) {
     //            var_dump($_FILES);die;
     //        }
     if ($model->load(Yii::$app->request->post())) {
         $file = UploadedFile::getInstance($model, 'file');
         $model->file = $file->name;
         if ($model->validate()) {
             $file->saveAs(Yii::$app->basePath . '/uploads/' . $file->baseName . '.' . $file->extension);
             $model->processCsv($file);
         }
     }
     return $this->renderAjax('_upload_csv', ['model' => $model]);
 }