artkost/yii2-attachment

Yii 2 文件附件

安装: 46

依赖: 1

建议者: 0

安全: 0

星标: 3

关注者: 3

分支: 1

开放问题: 1

类型:yii2-extension

dev-master 2015-08-27 18:25 UTC

This package is auto-updated.

Last update: 2024-08-29 03:36:07 UTC


README

Build Status

此组件提供了附件和上传功能

默认情况下,所有上传的文件都存储在数据库中,并具有 临时 状态。

当带有附件的模型自行保存时,所有附加到模型的文件将更改为永久状态。

Cli 命令

php yii attachment/manager/clear 从系统中清除所有临时文件

如何使用

配置 Manager 组件

return [
    'components' => [
        'attachmentManager' => [
            'class' => 'artkost\attachment\Manager',
            'storageUrl' => '@web/storage',
            'storagePath' => '@webroot/storage',
            'attachmentFileTable' => '{{%attachment_file}}'
        ]
    ]
]

创建自己的文件类型

namespace app\modules\user\models;

use artkost\attachment\models\ImageFile;

class UserAvatarFile extends ImageFile
{
    const TYPE = 'userProfile';

    //subfolder of storgae folder
    public $path = 'user/profile';
}

创建具有 attachment_id 字段的模型,并将其附加到该模型上

注意:模型只能有一个行为实例

/**
 * Class Profile
 * @package app\modules\user\models
 * User profile model.
 *
 * @property integer $user_id User ID
 * @property string $name Name
 * @property string $surname Surname
 * @property int $avatar_id Avatar //our attachment_id
 * @property boolean $sex
 *
 * @property User $user User
 * @property UserAvatarFile $avatar avatar file
 */
class UserProfile extends ActiveRecord
{

    public static function tableName()
    {
        return '{{%user_profile}}';
    }

    public function behaviors()
    {
        return [
            'attachBehavior' => [
                'class' => AttachBehavior::className(),
                'models' => [
                    'avatar' => [
                        'class' => UserAvatarFile::className()
                    ]
                ]
            ]
        ];
    }

    public function getAvatar()
    {
        // simply helper method with predefined conditions
        return $this->hasOneAttachment('avatar', ['id' => 'avatar_id']);
    }
}

目前仅支持 FileAPI 上传,但您可以添加自己的。

向控制器中添加操作

namespace app\modules\user\controllers;

use artkost\attachmentFileAPI\actions\UploadAction as FileAPIUpload;
use app\modules\user\models\UserProfile;

/**
 * Profile controller for authenticated users.
 */
class ProfileController extends Controller
{

    public function actions()
    {
        return [
            'fileapi-upload' => [
                'class' => FileAPIUpload::className(),
                'modelClass' => UserProfile::className(),
                'attribute' => 'avatar'
                //'accessCheck' => function($action) {  }
            ]
        ];
    }

}

在操作视图文件中,您可以使用小部件上传文件

use artkost\attachmentFileAPI\widgets\File as FileAPIWidget;
?>
...
<?= $form->field($model, 'preview')->widget(
    FileAPIWidget::className(),
    [
        'url' => ['upload-preview'],
        'settings' => [
            'autoUpload' => true
        ]
    ]
)->label(false) ?>