Storage and Upload file for Yii2
file upload/resize, (*1)
Any contributions are welcome, (*2)
Preview
, (*3)
Crop Preview (large image), (*4)
Installation
The preferred way to install this extension is through composer., (*5)
Either run, (*6)
php composer.phar require --prefer-dist kak/storage "*"
or add, (*7)
"kak/storage": "*"
to the require section of your composer.json
file and run command composer update
, (*8)
Usage
PLS set config params Yii::$app->params, (*9)
/** @docs https://console.aws.amazon.com/iam/home Generation access key and secret */
$amazon_config = [
'key' => '',
'secret' => '',
'bucket' => 'my',
'level' => 2,
'type' => 'amazon',
'region' => 'us-east-1',
]
//...
'storage' => [
'storages' => [
// use amazon config
'photo' => $amazon_config,
'custom_name' => [],
// local server save files
'tmp' => [
'level' => 0,
],
],
],
Example use controller this uploading, (*10)
public function actions()
{
return [
'upload' => [
'class' => UploadAction::className(),
'form_name' => 'kak\storage\models\UploadForm',
'storage' => 'tmp', // save image default tmp storage
'resize_image' => [ // list formats
'preview' => [1024,1024, UploadAction::IMAGE_RESIZE, 'options' => [] ],
'thumbnail' => [120,120, UploadAction::IMAGE_THUMB],
'350' => [350,280, UploadAction::IMAGE_RESIZE],
]
],
];
}
resize_image.options
- animate if true then save image gif animated else first moveclip
- quality 10 - 100, (*11)
Save model then controller, (*12)
/**
* @param $id int edit post
* @return string
*/
public function actionUpdate($id)
{
$model = $this->findPostById($id);
$uploadForm = new \kak\storage\models\UploadForm(['meta_name' => 'image_base']);
$uploadForm->meta = $postModel->images_json;
if($this->savePostForm($model, $uploadForm)) {
return $this->redirect(['/dashboard/post/update','id' => $postModel->id]);
}
return $this->render('form',compact(
'model', 'uploadForm'
));
}
/**
* @param $model Post
* @param $uploadForm \kak\storage\models\UploadForm
* @return bool
*/
protected function savePostForm(&$model,&$uploadForm)
{
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$result = $uploadForm->saveToStorage('tmp','images',[]);
$model->images_json = Json::encode($result);
return $model->save();
}
return false;
}
Once the extension is installed, simply use it in your code by:, (*13)
<div>
<?=\kak\storage\Upload::widget([
'model' => $uploadFormModel,
'url' => ['/dashboard/default/upload', 'resize_type' => 'thumbnail,350']
]); ?>
</div>
<hr>
if arg name resize_type in GET only these types will be saved resize images, (*14)
usage pjax
register assets the main layouts, (*15)
StorageAsset::register($view);
pjax event add code, (*16)
$(document).on('pjax:end','.pjax-wrapper',function(e){
//init old gui
$('.kak-storage-upload').kakStorageUpload({});
});
roadmap
2018:
Q1 add storage google cloud, change guzzle http
to yii2-http-client
, change aws-sdk-php
Q2 create new uploader widget + tests, (*17)