public function upload() { $ds = DIRECTORY_SEPARATOR; //1 $storeFolder = PATH_UPLOAD . 'profile/'; //2 extract($_POST); if (!empty($_FILES)) { $filename = Str::sanitize($_FILES['file']['name']); if (copy($_FILES['file']['tmp_name'], $storeFolder . $filename)) { $id = DB::update('users', $_SESSION['user_id'], $section, array($section => $filename)); Image::resize_group($storeFolder, $filename); return array('success' => true, 'id' => $id); } return array("error" => "Could not write to fs"); } }
/** * Upload and resize product image * * 1. Get path * 2. Generate file name * 3. Upload * 4. Resize * 5. Delete old temporary image(s) * * @param \Symfony\Component\HttpFoundation\File\UploadedFile|array $file * @param string $currentImage * * @return array */ protected function _uploadProductImage($file, $currentImage) { // 1 $tempPath = config('front.temp_path'); // 2 $filename = new FileName($tempPath, $file->getClientOriginalExtension()); $filename->setPrefix(_const('PRODUCT_PREFIX'))->product()->generate(); $filename->group(['big' => ['width' => _const('PRODUCT_BIG'), 'height' => _const('PRODUCT_BIG')], 'medium' => ['width' => _const('PRODUCT_MEDIUM'), 'height' => _const('PRODUCT_MEDIUM')], 'thumb' => ['width' => _const('PRODUCT_THUMB'), 'height' => _const('PRODUCT_THUMB')]], false); // 3 $upload = new Upload($file); $upload->setDirectory($tempPath)->setName($filename->getName())->move(); // 4 $image = new Image($tempPath . $filename->getName()); $image->setDirectory($tempPath)->resizeGroup($filename->getGroup()); // 5 foreach ($this->_productImgSizes as $size) { $nameBySize = str_replace(_const('TOBEREPLACED'), "_{$size}", $currentImage); delete_file($tempPath . $nameBySize); } delete_file($tempPath . $currentImage); return ['image' => $image, 'temp_path' => $tempPath, 'filename' => $filename]; }
/** * 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); $fileModel = new File(); if ($model->load(Yii::$app->request->post())) { if (Yii::$app->request->isAjax) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return $model->validate($model); } if (!empty($_FILES)) { $fileModel->uploadFile = UploadedFile::getInstance($fileModel, 'uploadFile'); if ($fileModel->uploadFile && $fileModel->validate(['uploadFile'])) { $model->preview = Image::upload($fileModel->uploadFile); } } if ($model->save()) { //return $this->redirect(['view', 'id' => $model->id]); return $this->goBack(); } else { return $this->render('update', ['model' => $model, 'fileModel' => $fileModel]); } } else { if (Yii::$app->request->isAjax) { return $this->renderAjax('update', ['model' => $model, 'fileModel' => $fileModel]); } else { return $this->render('update', ['model' => $model, 'fileModel' => $fileModel]); } } }
echo $form->field($model, 'author_id')->dropDownList(ArrayHelper::map(Authors::getAllAuthors(), 'id', 'name'), ['prompt' => Yii::t('app', 'Выберите автора')]); ?> <?php echo $form->field($model, 'name')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'date_fabr')->widget(DatePicker::className(), ['language' => 'ru', 'clientOptions' => ['autoclose' => true, 'format' => 'dd/mm/yyyy'], 'options' => ['placeholder' => '12/31/2014']]); ?> <?php if ($model->preview) { ?> <img src="<?php echo Image::thumb($model->preview, 240); ?> "> <a href="<?php echo Url::to(['/books/admin/clear-image', 'id' => $model->primaryKey]); ?> " class="text-danger confirm-delete" title="<?php echo Yii::t('app', 'Clear image'); ?> "><?php echo Yii::t('app', 'Clear image'); ?> </a> <?php } ?>
/** * normalice * This method controlls files size and shape * @param [object] $file file to evaluated * @return [object] $file file normalized */ public function normalice($file) { $info = (object) pathinfo($file); $options = (object) $this->options; //images control if (@$options->type == 'img') { $img = \Image::make($file); $maxwidth = @$options->maxwidth ?: null; $maxheight = @$options->maxheight ?: null; //resizing images if (@$options->square) { //square picture $height = $img->height(); $width = $img->width(); $offset = floor(abs($width - $height) / 2); if ($height > $width) { $img->crop($width, $width, 0, $offset); } else { $img->crop($height, $height, $offset, 0); } } if ($maxwidth || $maxheight) { $img->resize($maxwidth, $maxheight, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); } $img->save(); } return $this; }
/** * Save user * * @param Illuminate\Http\Request $request * * @return response * * @throws \Exception */ public function save(Request $request) { if ($request->isMethod('POST')) { $edit = $request->has('id'); $user = $edit ? $this->_getUserById($request->get('id')) : $this->user; $rules = $this->user->rules(); $messages = $this->user->messages(); if ($edit && str_equal($user->username, $request->get('username'))) { $rules = remove_rules($rules, ['username.unique:users,username']); } if ($edit && str_equal($user->email, $request->get('email'))) { $rules = remove_rules($rules, ['email.unique:users,email']); } if ($edit) { $rules = remove_rules($rules, ['password.required']); } $validator = Validator::make($request->all(), $rules, $messages); if ($validator->fails()) { return back()->withInput()->withErrors($validator, 'all'); } try { $except = []; if ($request->password === '') { $except = ['password']; } $user = $this->bind($user, $request->all(), $except); if (!$edit) { $user->created_at = new \DateTime(); } $user->updated_at = new \DateTime(); //Upload avatar if ($request->hasFile('avatar')) { $avatarPath = config('back.avatar_path'); $file = $request->file('avatar'); $filename = new FileName($avatarPath, $file->getClientOriginalExtension()); $filename->avatar()->generate(); $filename->setPrefix(_const('AVATAR_PREFIX')); $filename->avatar()->group($this->_getAvatarGroup(), false); $upload = new Upload($file); $upload->setDirectory($avatarPath)->setName($filename->getName())->move(); $image = new Image($avatarPath . $upload->getName()); $image->setDirectory($avatarPath)->resizeGroup($filename->getGroup()); delete_file($avatarPath . $upload->getName()); $resizes = $image->getResizes(); $user->avatar = $resizes['small']; } $user->save(); } catch (Exception $ex) { throw new \Exception(_t('backend_common_opp') . $ex->getMessage()); } return redirect(route('backend_users'))->with('success', _t('backend_common_saved')); } }
?> <div class="books-index"> <h1><?php echo Html::encode($this->title); ?> </h1> <?php echo $this->render('_search', ['model' => $searchModel]); ?> <?php echo GridView::widget(['dataProvider' => $dataProvider, 'filterModel' => null, 'columns' => ['id', 'name', ['attribute' => 'preview', 'format' => 'html', 'value' => function ($data) { return Html::a(Html::img(Image::thumb($data['preview'], 100)), $data['preview'], ['class' => 'preview_pic']); }], ['attribute' => 'author_id', 'format' => 'html', 'label' => 'Автор', 'value' => function ($data) { return $data['author']['firstname'] . ' ' . $data['author']['lastname']; }], ['attribute' => 'date', 'format' => ['date', 'php:d F Y']], 'date_create:relativeTime', ['class' => 'yii\\grid\\ActionColumn', 'template' => '{update}{view}{delete}', 'buttons' => ['format' => 'raw', 'update' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, ['title' => 'Редактировать', 'class' => 'ajax_table fancybox.ajax']); }, 'view' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, ['title' => 'Просмотр', 'class' => 'ajax_table fancybox.ajax']); }]]]]); ?> <p> <?php echo Html::a(Yii::t('app', 'Добавить книгу'), ['create'], ['class' => 'btn btn-success']); ?> </p>
public function ajaxChangeCover(Request $request) { if ($request->isMethod('POST')) { $rules = $this->_getCoverRules(); $messages = $this->_getCoverMessages(); $validator = Validator::make($request->all(), $rules, $messages); if ($validator->fails()) { return file_pong(['status' => _const('AJAX_ERROR'), 'messages' => $validator->errors()->first()], 403); } /** * 1. Get file, path and info * 2. Generate file name * 3. Upload * 4. Resize * 5. Delete old cover images and upload image * 6. Save new info */ try { // 1 $store = store(); $coverPath = config('front.cover_path'); $file = $request->file('__file'); // 2 $filename = new FileName($coverPath, $file->getClientOriginalExtension()); $filename->cover()->generate(); $filename->setPrefix(_const('COVER_PREFIX')); $filename->cover()->group($this->_getCoverGroup(), true); // 3 $upload = new Upload($file); $upload->setDirectory($coverPath)->setName($filename->getName())->move(); // 4 $image = new Image($coverPath . $upload->getName()); $image->setDirectory($coverPath)->resizeGroup($filename->getGroup()); // 5 delete_file([$coverPath . $upload->getName(), $coverPath . $store->cover_original, $coverPath . $store->cover_big, $coverPath . $store->cover_medium, $coverPath . $store->cover_small]); // 5 $resizes = $image->getResizes(); $store->cover_original = $resizes['original']; $store->cover_big = $resizes['big']; $store->cover_medium = $resizes['medium']; $store->cover_small = $resizes['small']; $store->update(); } catch (Exception $ex) { $validator->errors()->add('__file', _t('opp')); return file_pong(['status' => _const('AJAX_OK'), 'messages' => $validator->errors()->first()], 500); } return file_pong(['status' => _const('AJAX_OK'), 'messages' => _t('saved_info'), 'data' => ['big' => asset($coverPath . $resizes['big']), 'medium' => asset($coverPath . $resizes['medium']), 'small' => asset($coverPath . $resizes['small'])]]); } }
/* @var $model app\modules\books\models\Books */ $this->title = $model->name; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Books'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="books-view"> <h1><?php echo Html::encode($this->title); ?> </h1> <?php if (!Yii::$app->request->isAjax) { ?> <p> <?php echo Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']); ?> <?php echo Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], ['class' => 'btn btn-danger', 'data' => ['confirm' => Yii::t('app', 'Are you sure you want to delete this item?'), 'method' => 'post']]); ?> </p> <?php } ?> <?php echo DetailView::widget(['model' => $model, 'attributes' => ['id', ['attribute' => 'author_id', 'format' => 'html', 'label' => 'Автор', 'value' => $model->author->firstname . ' ' . $model->author->lastname], 'name', ['attribute' => 'date', 'format' => ['date', 'php:d F Y']], 'date_create:relativeTime', ['attribute' => 'preview', 'format' => 'html', 'value' => Html::img(Image::thumb($model->preview, 240))]]]); ?> </div>