PHP code example of ptheofan / yii2-file-upload-behavior

1. Go to this page and download the library: Download ptheofan/yii2-file-upload-behavior library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ptheofan / yii2-file-upload-behavior example snippets


$model->avatar = UploadedFile::getInstance($model, 'file');
$model->save();

$url = $model->avatar->getVersion('sm')->getUrl();

echo $model->avatar;

public function behaviors(): array
    {
        return [
            'avatar' => [
                'class' => FileAttribute::class,
                'modelAttribute' => 'avatar_hash',
                'modelVirtualAttribute' => 'avatar',
                'generateAfterInsert' => true,
                'filenameGenerator' => [
                    'class' => CallbackFilenameGenerator::class,
                    'withExt' => false,
                    'callback' => static function(string $file, ActiveRecord $model, IFileAttribute $attr) {
                        return sprintf('%s-%s', $model->id, sha1_file($file));
                    }
                ],
                'versions' => [
                    [
                        // will produce 
                        'class' => PngBaseVersion::class,
                        'name' => 'sm',
                        'basePath' => '/avatars',
                        'baseUrl' => 'https://cdn.example.com/avatars',
                        'width' => 64,
                        'suffix' => '-sm',
                    ],
                    [
                        'class' => PngResizedVersion::class,
                        'name' => 'sm',
                        'basePath' => '/avatars',
                        'baseUrl' => 'https://cdn.example.com/avatars',
                        'width' => 64,
                        'suffix' => '-sm',
                    ],
                    [
                        'class' => PngResizedVersion::class,
                        'name' => 'md',
                        'basePath' => '/avatars',
                        'baseUrl' => 'https://cdn.example.com/avatars',
                        'width' => 256,
                        'suffix' => '-md',
                    ],
                    [
                        'class' => PngResizedVersion::class,
                        'name' => 'lg',
                        'basePath' => '/avatars',
                        'baseUrl' => 'https://cdn.example.com/avatars',
                        'width' => 512,
                        'suffix' => '-lg',
                    ],
                ],
            ],
        ];
    }