PHPackages                             platx/yii2-upload - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. platx/yii2-upload

AbandonedArchivedYii2-extension

platx/yii2-upload
=================

Useful upload behavior for Yii Framework 2

1172PHP

Since Aug 10Pushed 8y ago2 watchersCompare

[ Source](https://github.com/platx/yii2-upload)[ Packagist](https://packagist.org/packages/platx/yii2-upload)[ RSS](/packages/platx-yii2-upload/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Yii2 Upload behavior
====================

[](#yii2-upload-behavior)

Behavior for ActiveRecord models for easy file uploading. Following formats of uploads are supported:

- POST method upload ()
- Remote file url
- Base64
- Server path

Package includes 3 classes:

- FileUploadBehavior - main behavior to handle files
- ImageUploadBehavior - extended class to handle image files, includes functional to fix image orientation for jpeg images, parameter `originalFolder` to store files in original size folder (for ImageAction)
- ImageAction - makes different sizes for images, that stores resized files to folder near original folder, named "{width}x{height}.

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist platx/yii2-upload "*"

```

or add

```
"platx/yii2-upload": "*"

```

to the require section of your `composer.json` file.

Configuring
-----------

[](#configuring)

Attach the behavior in your ActiveRecord model:

```
public function behaviors()
{
    return [
        'upload' => [
            'class' => 'platx\upload\FileUploadBehavior',
            // or 'class' => 'platx\upload\ImageUploadBehavior',
            'attributes' => ['image'], // Model attributes to handle
            'scenarios' => ['default'], // Scenarios to handle
            'basePath' => '@app/web/uploads', // Base path on server to store files
            'baseUrl' => '/uploads', // Base url to make url
            // Additional configuration
        ]
    ];
}
```

Configuration options for platx\\upload\\FileUploadBehavior:

- **attributes** - Model attribute names that should be handled. Type: `array`. `Required parameter`.
- **scenarios** - Scenarios to handle (by default scenarios from owner model taken). Type: `array`.
- **prefix** - Prefix for file attribute, which will be posted. Type: `string`. Default value: `file_`.
- **basePath** - Server path to store files (with alias or absolute server path). Type: `string`. Default value: `@app/web/uploads`.
- **baseUrl** - Base url to build url link to file. Type: `string`. Default value: `/uploads`.
- **handleNotUploadedFiles** - Whether handle not POST method uploads (*base64*, *remote url*, *server path*). Type: `boolean`. Default value: `false`.
- **nameTemplate** - File name template or generating new name. Default value: `{id}_{name}.{ext} `. Can be:
    - `true` - Generate new file name
    - `false` - Keep original file name
    - `string` - Template to generate new file name, can be with variables:
        - `{id}` - Record id (if is composite key, will be imploded)
        - `{attribute}` - Model attribute name
        - `{name}` - File name
        - `{ext}` - File extension
    - `\Closure` - the callback function to be executed. The anonymous function should have the following signature: ```
        function ($model, $attribute, $file)
        ```

        where: - `$model` - Owner model instance - `$attribute` - Current attribute name for file upload - `$file` - Current UploadedFile instance to save For example: ```
        function ($model, $attribute, $file) {
            return 'file_' . $model->id . '.' .$file->extension;
        }
        ```
- **modelFolder** - Whether add model name folder. Default value: `true`. Can be:
    - `true` - Include model folder
    - `false` - Do not include model folder
    - `string` - Static string to be included
    - `\Closure` - The callback function to be executed. The anonymous function should have the following signature: ```
        function ($model, $attribute, $file)
        ```

        where: - `$model`: Owner model instance - `$attribute`: Current attribute name for file upload - `$file`: Current UploadedFile instance to upload For example: ```
        function ($model, $attribute, $file) {
            return 'my_' . $model::getTableSchema()->fullName;
        }
        ```
- **dynamicFolder** - Whether generate dynamic folder. Default value: `true`. Can be:
    - `true` - Generate dynamic folder (3 nesting levels), using model primary key
    - `false` - Do not include dynamic folder
    - `string` - Static string
    - `\Closure` - The callback function to be executed. The anonymous function should have the following signature: ```
        function ($model, $attribute, $file)
        ```

        where: - `$model`: Owner model instance - `$attribute`: Current attribute name for file upload - `$file`: Current UploadedFile instance to upload For example: ```
        function ($model, $attribute, $file) {
            return $model::getTableSchema()->fullName . '_' .uniqid();
        }
        ```
- **attributeFolder** - Whether add attribute folder. Default value: `true`. Can be:
    - `true` - Add folder with attribute name
    - `false` - Do not include attribute folder
    - `string` - Static string
    - `\Closure` - The callback function to be executed. The anonymous function should have the following signature: ```
        function ($model, $attribute, $file)
        ```

        where: - `$model`: Owner model instance - `$attribute`: Current attribute name for file upload - `$file`: Current UploadedFile instance to upload For example: ```
        function ($model, $attribute, $file) {
            return $model::getTableSchema()->fullName . '_' .uniqid();
        }
        ```
- **instanceByName** - Whether get file instance by attribute name. Type: `boolean`. Default value: `false`.
- **deleteWithOwner** - Whether delete file with model record deleting. Type: `boolean`. Default value: `true`.
- **deleteTempFile** - Whether delete temporary file after saving. Type: `boolean`. Default value: `true`.
- **messageUploadNotSupported** - Error message if upload type is not supported. Type: `string`. Default value: `From message source`.
- **messageUnableSaveFile** - Error message if unable to save file to destination folder. Type: `string`. Default value: `From message source`.
- **messageUnableHandleFile** - Error message if unable to handle upload and make UploadedFile instance. Type: `string`. Default value: `From message source`.
- **messageUnableCreateDirectory** - Error message if unable to create destination folder for file. Type: `string`. Default value: `From message source`.
- **originalFolder**(ImageUploadBehavior) - Folder name to store original image files (can be changed in ImageUploadBehavior). Type: `string`. Default value: `original`.

Then to enable file validation you should add it to rules array of your model, like this:

```
public function rules()
{
    return [
        ['file_image', 'file'],
        // or
        ['file_image', 'image'],
    ];
}
```

Attach the image action in your controller class:

```
public function actions()
{
    return [
        'upload' => [
            'image' => [
                'class' => \platx\upload\ImageAction::className(),
                'basePath' => '@app/web/uploads',
                'originalFolder' => 'original',
                'sizeList' => ['500x500','200x0','0x300']
            ],
        ]
    ];
}
```

where:

- `sizeList` - Allowed size list of generated images, if is empty, any size is allowed to resize. If you will put 0 to width or height, it will be dynamic to save image ratio.
- `basePath` - Base server path to image uploads
- `originalFolder` - Folder name with original image files

Add following to your UrlManager component rules:

```
    '/uploads/x/' => '/your_controller/image'

```

Usage
-----

[](#usage)

To upload file, use attribute name `{prefix}_{attribute}`. To get file url, use function `getFileUrl($attribute, $isAbsolute)` for FileUploadBehavior and `getFileUrl($attribute, $isAbsolute, $size)` for ImageUploadBehavior with ImageAction configured, where:

- $attribute - your attribute name
- $isAbsolute - whether to make your file url absolute or not (with http/https and your site domain)
- $size - Size to needed size of image in `{width}x{height}` format

For example, you have attribute named `image` and behavior property `prefix` equals `file_`. To upload file, you should use attribute `file_image`. To get file url, you should use function of your model `$model->getFileUrl('image')`.

Example form file:

```

```

Example view file:

```

```

or using with ImageAction configured:

```

```

###  Health Score

21

—

LowBetter than 19% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/029e59818b14c6d88b7e657064d8a530bb8b1aa08053ea943f064eb32f0dbf0f?d=identicon)[asdixer](/maintainers/asdixer)

---

Top Contributors

[![platx](https://avatars.githubusercontent.com/u/5385861?v=4)](https://github.com/platx "platx (14 commits)")

### Embed Badge

![Health badge](/badges/platx-yii2-upload/health.svg)

```
[![Health](https://phpackages.com/badges/platx-yii2-upload/health.svg)](https://phpackages.com/packages/platx-yii2-upload)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
