itstructure/yii2-multi-format-uploader Module for Yii2 Framework to upload some type of files to local or S3 Amazon storage

fileuploadamazonmodulelocal

Yii2 Multi format uploader module - MFUploader

Introduction

Latest Stable Version Latest Unstable Version License Total Downloads Build Status Scrutinizer Code Quality

MFUploader -- Module for the Yii2 Framework to upload some type of files to local or S3 Amazon storage. MFUploader module provides the following options:

  • Upload files to local storage.
  • Upload files to remote Amazon S3 storage.
  • Support file formats: image, audio, video, application, text.
  • Link uploaded files with external application owners (pages, articles, posts e.t.c...).
  • Manage internal albums: imageAlbum, audioAlbum, videoAlbum, applicationAlbum, textAlbum, otherAlbum.
  • Link uploaded files with internal albums (owners).
  • Link internal albums with the external owners (pages, articles, posts e.t.c...).

To work with image binary content it uses Yii2 imagine. To work with Amazon it uses AWS SDK.

Base project examples, which use this MFUploader module:

yii2-template-multilanguage.

yii2-template-simple.

Addition module description you can see in my Personal site.

Requirements

  • php >= 7.1
  • composer
  • MySql >= 5.5
  • One of the next php extensions: GD|Imagick|Gmagick

Installation

Base install

Via composer:

composer require itstructure/yii2-multi-format-uploader ~3.2.7

If you are testing this package from local server directory

In application composer.json file set the repository, like in example:

"repositories": [
    {
        "type": "path",
        "url": "../yii2-multi-format-uploader",
        "options": {
            "symlink": true
        }
    }
],

Here,

yii2-multi-format-uploader - directory name, which has the same directory level like application and contains yii2 multi format uploader package.

Then run command:

composer require itstructure/yii2-multi-format-uploader:dev-master --prefer-source

Apply module migrations

For that make next, if not already done:

  • Define mfuploader module in application console config file:

    use Itstructure\MFUploader\Module as MFUModule;
    'modules' => [
        'mfuploader' => [
            'class' => MFUModule::class,
        ],
    ],
  • In file yii, that is located in application root directory, set @mfuploader alias:

    $application = new yii\console\Application($config);
    
    \Yii::setAlias('@mfuploader', $application->getModule('mfuploader')->getBasePath());
    
    $exitCode = $application->run();

    OR

    use Itstructure\MFUploader\Module as MFUModule;
    $application = new yii\console\Application($config);
    
    \Yii::setAlias('@mfuploader', MFUModule::getBaseDir());
    
    $exitCode = $application->run();
  • Run command in console:

    yii migrate --migrationPath=@mfuploader/migrations

    The data base structure:

    Data base structure

Usage

Main properties

The name of module: mfuploader

The namespace for used classes: Itstructure\MFUploader.

The alias to access in to module root directory: @mfuploader.

Application config

Base application config must be like in example below:

use Itstructure\MFUploader\Module as MFUModule;
use Itstructure\MFUploader\controllers\ManagerController;
use Itstructure\MFUploader\controllers\upload\{
    LocalUploadController,
    S3UploadController
};
use Itstructure\MFUploader\controllers\album\{
    ImageAlbumController,
    AudioAlbumController,
    VideoAlbumController,
    ApplicationAlbumController,
    TextAlbumController,
    OtherAlbumController
};
use Itstructure\MFUploader\components\{
    LocalUploadComponent,
    S3UploadComponent
};
'modules' => [
    'mfuploader' => [
        'class' => MFUModule::class, // REQUIRED
        'layout' => ...path to layout..., // NOT REQUIRED
        'view' => ...view component config..., // NOT REQUIRED
        'controllerMap' => [ // CUSTOM
            'upload/local-upload' => LocalUploadController::class,
            'upload/s3-upload' => S3UploadController::class,
            'managers' => ManagerController::class,
            'image-album' => ImageAlbumController::class,
            'audio-album' => AudioAlbumController::class,
            'video-album' => VideoAlbumController::class,
            'application-album' => ApplicationAlbumController::class,
            'text-album' => TextAlbumController::class,
            'other-album' => OtherAlbumController::class,
        ],
        'accessRoles' => ['admin', 'manager', e.t.c...], // CUSTOM
        'defaultStorageType' => MFUModule::STORAGE_TYPE_S3, // CUSTOM
        'components' => [ // CUSTOM
            'local-upload-component' => [ // CUSTOM
                'class' => LocalUploadComponent::class,
                'checkExtensionByMimeType' => false,
                'uploadRoot' => dirname($_SERVER['SCRIPT_FILENAME'])
            ],
            's3-upload-component' => [ // CUSTOM
                'class' => S3UploadComponent::class,
                'checkExtensionByMimeType' => false,
                'credentials' => require __DIR__ . '/aws-credentials.php',
                'region' => 'us-west-2',
                's3DefaultBucket' => 'bucketname',
            ],
        ],
        'publicBaseUrl' => 'http://your-site-address.com'
    ],
],

Here publicBaseUrl for example can be a project domain (http://your-site-address.com). If we have url in mediafiles table \uploads\images\imagealbum\0d\3890\a947f268d6f9fd02d8a0d7e147da922c.jpg, and we use getViewUrl() function from a mediafile model for local files, then for example a result link to image for src attribute of <img> tag will be:

http://your-site-address.com/uploads/images/imagealbum/0d/3890/a947f268d6f9fd02d8a0d7e147da922c.jpg

Note: It is not necessary to configure two components: local-upload-component and s3-upload-component. You must configure minimum one component, according with the defaultStorageType.

File field for the view template

File field must be rendered by FileSetter widget.

It is necessary to send an ID or URL of uploaded mediafile to you application controller and set in model. An after that to link mediafile ID with owner.

Example (for image files):

use Itstructure\MFUploader\widgets\FileSetter;
use Itstructure\MFUploader\Module as MFUModule;
use Itstructure\MFUploader\interfaces\UploadModelInterface;
Container to display selected image.
<div class="media">
    <div id="mediafile-container">
    </div>
    <div class="media-body">
        <h4 id="title-container" class="media-heading"></h4>
        <div id="description-container"></div>
    </div>
</div>
echo FileSetter::widget([
    'model' => $model,
    'attribute' => UploadModelInterface::FILE_TYPE_IMAGE,
    'neededFileType' => UploadModelInterface::FILE_TYPE_IMAGE,
    'buttonName' => MFUModule::t('main', 'Set image'),
    'options' => [
        'id' => Html::getInputId($model, UploadModelInterface::FILE_TYPE_IMAGE)
    ],
    'mediafileContainer' => '#mediafile-container',
    'titleContainer' => '#title-container',
    'descriptionContainer' => '#description-container',
    'owner' => 'post', // can be page, article, catalog e.t.c...
    'ownerId' => {current owner id, post id, page id e.t.c.},
    'ownerAttribute' => UploadModelInterface::FILE_TYPE_IMAGE,
    'subDir' => 'post' // can be page, article, catalog e.t.c...
]);

Configure upload components

Base attributes in BaseUploadComponent

Note: BaseUploadComponent - the base class, which LocalUploadComponent and S3UploadComponent extend.

To understand the principles of configure the base attributes, see public attributes in components\BaseUploadComponent class. But it may be difficult to configure thumbsConfig and thumbFilenameTemplate. Attribute thumbsConfig takes the values according with the next chain:

  1. From the default config file config/thumbs-config.php in module init() function.
  2. Can be rewrited by custom during module thumbsConfig attribute.
  3. Previous config result inserted in to the LocalUploadComponent and S3UploadComponent module components.
  4. Configuration thumbsConfig in module components can be rewrited by custom during component thumbsConfig attribute.

Attributes in LocalUploadComponent

That is very simple. See public attributes in components\LocalUploadComponent class.

Attributes in S3UploadComponent

See public attributes in components\S3UploadComponent class. But there are important attributes:

  • credentials. Attribute to access in to Amazon web services account. Can be: array, callable, and other. See https://docs.aws.amazon.com/aws-sdk-php/v3/guide/guide/credentials.html.
  • s3DefaultBucket - bucket, which you use to upload files as default.
  • s3Buckets - buckets to upload files depending on the owner. Not required.

    config example:

    's3Buckets' => [
      'post' => 'bucketWithPosts',
      'page' => 'bucketWithPages',
      'imageAlbum' => 'bucketWithImages',
      'audioAlbum' => 'bucketWithAudio',
    ]

For more information of S3 configuration, see the next links:

Link entities with owners

To link entities (mediafiles and albums) with owners (pages, articles, posts e.t.c...) there is the abstract class behaviors\Behavior.

You must use child classes: behaviors\BehaviorMediafile and behaviors\BehaviorAlbum.

Explanation by example.

You have a catalog model which extends an ActiveRecord yii2 class.

Use a behaviors\BehaviorMediafile and behaviors\BehaviorAlbum in behaviors of your catalog model to link mediafiles and albums with catalog after: insert active record, update active record, delete active record:

use Itstructure\MFUploader\behaviors\{BehaviorMediafile, BehaviorAlbum};
use Itstructure\MFUploader\interfaces\UploadModelInterface;
use Itstructure\MFUploader\models\album\Album;
public $thumbnail;

public $imageAlbum = [];

public function behaviors()
{
    return ArrayHelper::merge(parent::behaviors(), [
        'mediafile' => [
            'class' => BehaviorMediafile::class,
            'name' => static::tableName(),
            'attributes' => [
                UploadModelInterface::FILE_TYPE_THUMB,
            ],
        ],
        'albums' => [
            'class' => BehaviorAlbum::class,
            'name' => static::tableName(),
            'attributes' => [
                Album::ALBUM_TYPE_IMAGE,
            ],
        ],
    ]);
}

Note: This block should be used in conjunction with the FileSetter widget inside the view form template!

Here the following happens:

  • If you use a "thumbnail" name of attribute param in FileSetter widget, the uploaded mediafile (thumbnail) will be linked with catalog after insert new catalog data to the data base.
  • If you use an "imageAlbum" (by Album::ALBUM_TYPE_IMAGE) name of the name attribute of dropdown or checkbox html field, the last created image album will be linked with catalog after insert new catalog data to the data base.

That works according with the next data base example structure:

Table "mediafiles" - record with id=20 now inserted.

| id  | ... |      created_at     |      updated_at     |
|-----|-----|---------------------|---------------------|
| ... | ... |         ...         |         ...         |
| 20  | ... | 2018-05-06 21:35:04 | 2018-05-06 21:35:10 |

Table "catalog" - record with id=10 inserted after create mediafile (id=20).

| id  | ... |      created_at     |      updated_at     |
|-----|-----|---------------------|---------------------|
| ... | ... |         ...         |         ...         |
| 10  | ... | 2018-05-06 21:35:20 | 2018-05-06 21:35:25 |

Table "owners_mediafiles"

| mediafileId | ownerId |   owner   |  ownerAttribute  |
|-------------|---------|-----------|------------------|
|     ...     |   ...   |    ...    |        ...       |
|     20      |    10   |  catalog  |     thumbnail    |

Table "albums"

| id  |     type    | ... |      created_at     |      updated_at     |
|-----|-------------|-----|---------------------|---------------------|
| ... |     ...     | ... |         ...         |         ...         |
|  5  | imageAlbum  | ... | 2018-05-06 21:30:00 | 2018-05-06 21:30:05 |

Table "owners_albums"

| albumId | ownerId |   owner   |  ownerAttribute  |
|---------|---------|-----------|------------------|
|   ...   |   ...   |    ...    |        ...       |
|    5    |    10   |  catalog  |    imageAlbum    |

Note: If you set in FileSetter widget the attributes: owner, ownerId, ownerAttribute - linking entity with owner will be done automatically during ajax request in uploadmanager.

Integrated album controllers

There are already integrated album controllers in the namespace: Itstructure\MFUploader\controllers\album. Controllers provide the work with the next types of albums: imageAlbum, audioAlbum, videoAlbum, applicationAlbum, textAlbum, otherAlbum.

For that controllers there are already the models and view templates.

To work with that, you must set just the routes in application configuration.

License

Copyright © 2018-2023 Andrey Girnik girnikandrey@gmail.com.

Licensed under the MIT license. See LICENSE.txt for details.

Changelog

CHANGE LOG:

3.2.7 January 23, 2023:

  • Readme fix.

3.2.6 January 22, 2023:

  • Improve scrutinizer config.

3.2.5 January 18, 2023:

  • Upgrade copyright year.

3.2.4 April 18, 2021:

  • Bug fix: Unparenthesized a ? b : c ? d : e is not supported.

3.2.3 April 17, 2021:

  • Bug fix: Call to a member function validateCsrfToken() on string.

3.2.2 February 23, 2021:

  • Upgrade copyright year.

3.2.1 September 12, 2020:

  • Allow set null for one width or height in ThumbConfig.

3.2.0 September 12, 2020:

  • Optimize deleteMediafiles() method in MediaFilesTrait. Add protection to physical delete multiplied files, which are related more then one owner.
  • Optimize owner's entity classes.

3.1.1 August 10, 2020:

  • Add module attribute useInitialThumbsConfig with default value true.

3.1.0 August 07, 2020:

  • Increase alt and title string sizes to 128 for mediafiles table.

3.0.2 July 22, 2020:

  • Use array_merge() instead ArrayHelper::merge() to merge default thumb and preview configs with custom.

3.0.1 July 17, 2020:

  • Bug fix for registerTranslations() method. Set it static.

3.0.0 July 15, 2020:

  • Set string sizes for migration columns no more 128 (and 64) to support old MySql database versions.
  • Solve the installation issue: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes.
  • Fixes for small bugs.

2.2.2 June 23, 2020:

  • Modify README syntax.

2.2.1 June 20, 2020:

  • Bug fix for getThumbUrl() method in Mediafile model.

2.2.0 June 15, 2020:

  • Change saving local file url to DB.
  • Add publicBaseUrl param to Module for full local files url.
  • Add getViewUrl() to getting file's url with a public base url just for local storage.

2.1.5 June 9, 2020:

  • Documentation upgrade. Change link to personal site.

2.1.4 August 19, 2019:

  • Upgrade of the copyright time and add a personal site link.

2.1.3 August 19, 2019:

  • Bug fix for set an unique name of uploading file. Used microtime() in LocalUpload and S3Upload models.

2.1.2 June 12, 2019:

  • Optimize getting module object from a mediafile in getModule() function.

2.1.1 June 01, 2019:

  • Set ability for collable type of preview options location parameter. Used in getPreviewOptions() module method if is_callable($previewOptions[$location]).

2.1.0 May 18, 2019:

  • Add urlPrefix parameter in to AlbumController for redirect and view links.
  • Add urlPrefixNeighbor parameter in to AlbumController for view links of neighbor entity.

2.0.1 August 9, 2018:

  • Delete duplicates and optimize code.

2.0.0 August 9, 2018:

  • Code fixes according with the PSR standards:
    • Correct in functions ){ to ) {.
    • Add space before and after the @param function comment option.
    • Renaming controllers and models to a single entity name.
    • Renaming module constants.
    • Some simple code fixes.
  • Add file_exists() check function in to sendFile() of the LocalUpload model.
  • Fixes for README.

1.0.0 May 15, 2018:

  • Create module with the following options:
    • Upload files to local storage.
    • Upload files to remote Amazon S3 storage.
    • Support file formats: image, audio, video, application, text.
    • Link uploaded files with external application owners (pages, articles, posts e.t.c...).
    • Manage internal albums: imageAlbum, audioAlbum, videoAlbum, applicationAlbum, textAlbum, otherAlbum.
    • Link uploaded files with internal albums (owners).
    • Link internal albums with the external owners (pages, articles, posts e.t.c...).
  • Created documentation.

Statistics

Downloads
GitHub Stars
GitHub Forks

Releases

Comments



3.2.7 is the latest of 25 releases



MIT license
Stats
5 github stars & 2 github forks
0 downloads in the last day
2 downloads in the last 30 days
315 total downloads