Need help with yii2-upload-behavior?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

mohorev
129 Stars 54 Forks Other 68 Commits 5 Opened issues

Description

File/image upload behavior for Yii 2

Services available

!
?

Need anything else?

Contributors list

# 44,001
PHP
Yii Fra...
yii2
Twitter
42 commits
# 181,930
PHP
pointer...
CSS
vhost
4 commits
# 309,751
PHP
CSS
Yii Fra...
2 commits
# 242,214
Node.js
CSS
Express
excepti...
2 commits
# 18,955
PHP
Ruby
slate
Shell
1 commit
# 394,385
sitemap...
PHP
Laravel
CSS
1 commit
# 709,218
PHP
1 commit
# 529,962
PHP
Java
Android
1 commit
# 351,422
yii2
html-pa...
XML
xml-par...
1 commit
# 153,689
yii2-wi...
PHP
CSS
yii2
1 commit

Upload behavior for Yii 2

This behavior automatically uploads file and fills the specified attribute with a value of the name of the uploaded file. This code is inspired by, but not derived from, https://github.com/yii-dream-team/yii2-upload-behavior.

Latest Version Software License Build Status Quality Score

Installation

The preferred way to install this extension via composer.

Either run

php composer.phar require --prefer-dist mohorev/yii2-upload-behavior "*"

or add this code line to the

require
section of your
composer.json
file:
"mohorev/yii2-upload-behavior": "*"

Usage

Upload file

Attach the behavior in your model:

class Document extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['file', 'file', 'extensions' => 'doc, docx, pdf', 'on' => ['insert', 'update']],
        ];
    }

/**
 * @return \yii\db\ActiveQuery
 */
public function getCategory()
{
    return $this->hasOne(Category::class, [ 'id' => 'id_category' ]);
}

/**
 * @inheritdoc
 */
function behaviors()
{
    return [
        [
            'class' => UploadBehavior::class,
            'attribute' => 'file',
            'scenarios' => ['insert', 'update'],
            'path' => '@webroot/upload/docs/{category.id}',
            'url' => '@web/upload/docs/{category.id}',
        ],
    ];
}

}

Set model scenario in controller action:

class Controller extends Controller
{
    public function actionCreate($id)
    {
        $model = $this->findModel($id);
        $model->setScenario('insert'); // Note! Set upload behavior scenario.

    ...
    ...
}

}

Example view file:

 ['enctype' => 'multipart/form-data']]); ?>
    = $form->field($model, 'image')->fileInput() ?>
    
= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>

Upload image and create thumbnails

Thumbnails processing requires yiisoft/yii2-imagine to be installed.

Attach the behavior in your model:

class User extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['image', 'image', 'extensions' => 'jpg, jpeg, gif, png', 'on' => ['insert', 'update']],
        ];
    }

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => \mohorev\file\UploadImageBehavior::class,
            'attribute' => 'image',
            'scenarios' => ['insert', 'update'],
            'placeholder' => '@app/modules/user/assets/images/userpic.jpg',
            'path' => '@webroot/upload/user/{id}',
            'url' => '@web/upload/user/{id}',
            'thumbs' => [
                'thumb' => ['width' => 400, 'quality' => 90],
                'preview' => ['width' => 200, 'height' => 200],
                'news_thumb' => ['width' => 200, 'height' => 200, 'bg_color' => '000'],
            ],
        ],
    ];
}

}

Example view file:

 ['enctype' => 'multipart/form-data']]); ?>
    
= Html::img($model->getUploadUrl('image'), ['class' => 'img-thumbnail']) ?>
= Html::img($model->getThumbUploadUrl('image'), ['class' => 'img-thumbnail']) ?>
= Html::img($model->getThumbUploadUrl('image', 'preview'), ['class' => 'img-thumbnail']) ?>
= $form->field($model, 'image')->fileInput(['accept' => 'image/*']) ?>
= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>

Behavior Options

  • attribute - The attribute which holds the attachment
  • scenarios - The scenarios in which the behavior will be triggered
  • instanceByName - Getting file instance by name, If you use UploadBehavior in
    RESTfull
    application and you do not need a prefix of the model name, set the property
    instanceByName = false
    , default value is
    false
  • path - the base path or path alias to the directory in which to save files.
  • url - the base URL or path alias for this file
  • generateNewName - Set true or anonymous function takes the old filename and returns a new name, default value is
    true
  • unlinkOnSave - If
    true
    current attribute file will be deleted, default value is
    true
  • unlinkOnDelete - If
    true
    current attribute file will be deleted after model deletion.
  • deleteOriginalFile - Only for UploadImageBehavior. If
    true
    original image file will be deleted after thumbs generating, default value is
    false
    .

Attention!

It is prefered to use immutable placeholder in

url
and
path
options, other words try don't use related attributes that can be changed. There's bad practice. For example:
class Track extends ActiveRecord
{
    public function getArtist()
    {
        return $this->hasOne(Artist::class, [ 'id' => 'id_artist' ]);
    }

public function behaviors()
{
    return [
        [
            'class' => UploadBehavior::class,
            'attribute' => 'image',
            'scenarios' => ['default'],
            'path' => '@webroot/uploads/{artist.slug}',
            'url' => '@web/uploads/{artist.slug}',
        ],
    ];
}

}

If related model attribute

slug
will change, you must change folders' names too, otherwise behavior will works not correctly.

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.