ldar/yii2-file-kit

Yii2 文件上传和存储套件

维护者

详细信息

github.com/ldar/yii2-file-kit

源代码

安装: 9

依赖: 0

建议者: 0

安全: 0

星级: 0

观察者: 2

分支: 105

类型:yii2-extension

1.2.2 2020-02-11 04:54 UTC

README

Packagist Dependency Status

本套件旨在自动化上传文件的常规流程,包括它们的保存和存储。它包括

  • 文件上传小部件(基于Blueimp 文件上传
  • 存储文件组件(基于flysystem
  • 下载、删除和查看(下载)文件的操作
  • 在模型中保存文件并在删除模型时删除文件的行为

这里您可以查看可用的文件系统适配器列表

演示

由于文件套件是yii2-starter-kit的一部分,其演示可以在启动套件演示这里找到。

安装

安装此扩展的首选方式是通过composer

运行

php composer.phar require trntv/yii2-file-kit

或在您的composer.json文件的require部分中添加

"trntv/yii2-file-kit": "@stable"

文件存储

要使用文件套件,您需要首先配置FileStorage。该组件是文件系统的一层抽象

  • 其主要任务是为每个文件生成唯一的名称并触发相应的事件。
'fileStorage'=>[
    'class' => 'trntv\filekit\Storage',
    'baseUrl' => '@web/uploads'
    'filesystem'=> ...
        // OR
    'filesystemComponent' => ...    
],

有几种方法可以配置trntv\filekit\Storage以与flysystem一起工作。

使用闭包

'fileStorage'=>[
    ...
    'filesystem'=> function() {
        $adapter = new \League\Flysystem\Adapter\Local('some/path/to/storage');
        return new League\Flysystem\Filesystem($adapter);
    }
]

使用文件系统构建器

  • 创建一个实现trntv\filekit\filesystem\FilesystemBuilderInterface的构建器类,并实现返回文件系统对象的build方法。请参阅examples/
  • 添加到您的配置
'fileStorage'=>[
    ...
    'filesystem'=> [
        'class' => 'app\components\FilesystemBuilder',
        'path' => '@webroot/uploads'
        ...
    ]
]

http://flysystem.thephpleague.com/上了解更多关于flysystem的信息

使用第三方扩展

  • 创建文件系统组件(示例使用creocoder/yii2-flysystem
'components' => [
    ...
    'fs' => [
        'class' => 'creocoder\flysystem\LocalFilesystem',
        'path' => '@webroot/files'
    ],
    ...
]
  • 在存储配置中设置文件系统组件名称
'components' => [
    ...
    'fileStorage'=>[
        'filesystemComponent'=> 'fs'
    ],
    ...
]

操作

文件套件包含几个用于处理上传的操作。

上传操作

设计用于保存小部件上传的文件

public function actions(){
    return [
           'upload'=>[
               'class'=>'trntv\filekit\actions\UploadAction',
               //'deleteRoute' => 'my-custom-delete', // my custom delete action for deleting just uploaded files(not yet saved)
               //'fileStorage' => 'myfileStorage', // my custom fileStorage from configuration
               'multiple' => true,
               'disableCsrf' => true,
               'responseFormat' => Response::FORMAT_JSON,
               'responsePathParam' => 'path',
               'responseBaseUrlParam' => 'base_url',
               'responseUrlParam' => 'url',
               'responseDeleteUrlParam' => 'delete_url',
               'responseMimeTypeParam' => 'type',
               'responseNameParam' => 'name',
               'responseSizeParam' => 'size',
               'deleteRoute' => 'delete',
               'fileStorage' => 'fileStorage', // Yii::$app->get('fileStorage')
               'fileStorageParam' => 'fileStorage', // ?fileStorage=someStorageComponent
               'sessionKey' => '_uploadedFiles',
               'allowChangeFilestorage' => false,
               'validationRules' => [
                    ...
               ],
               'on afterSave' => function($event) {
                    /* @var $file \League\Flysystem\File */
                    $file = $event->file
                    // do something (resize, add watermark etc)
               }
           ]
       ];
}

在相应的类中查看附加设置

删除操作

public function actions(){
    return [
       'delete'=>[
           'class'=>'trntv\filekit\actions\DeleteAction',
           //'fileStorage' => 'fileStorageMy', // my custom fileStorage from configuration(such as in the upload action)
       ]
    ];
}

在相应的类中查看附加设置

查看(下载)操作

public function actions(){
    return [
       'view'=>[
           'class'=>'trntv\filekit\actions\ViewAction',
       ]
    ];
}

在相应的类中查看附加设置

上传小部件

独立使用

echo \trntv\filekit\widget\Upload::widget([
    'model' => $model,
    'attribute' => 'files',
    'url' => ['upload'],
    'sortable' => true,
    'maxFileSize' => 10 * 1024 * 1024, // 10Mb
    'minFileSize' => 1 * 1024 * 1024, // 1Mb
    'maxNumberOfFiles' => 3 // default 1,
    'acceptFileTypes' => new JsExpression('/(\.|\/)(gif|jpe?g|png)$/i'),
    'showPreviewFilename' => false,
    'clientOptions' => [ ...other blueimp options... ]
]);

与ActiveForm一起使用

echo $form->field($model, 'files')->widget(
    '\trntv\filekit\widget\Upload',
    [
        'url' => ['upload'],
        'sortable' => true,
        'maxFileSize' => 10 * 1024 * 1024, // 10 MiB
        'maxNumberOfFiles' => 3,
        'clientOptions' => [ ...other blueimp options... ]
    ]
);

上传小部件事件

上传小部件触发一些内置的blueimp事件

  • 开始
  • 失败
  • 完成
  • 始终

您可以直接使用它们或在选项中添加自定义处理程序

'clientOptions' => [ 
    'start' => new JsExpression('function(e, data) { ... do something ... }'),
    'done' => new JsExpression('function(e, data) { ... do something ... }'),
    'fail' => new JsExpression('function(e, data) { ... do something ... }'),
    'always' => new JsExpression('function(e, data) { ... do something ... }'),
 ]

上传行为

此行为旨在在相应的关联中保存上传的文件

在模型某处

对于多个文件

 public function behaviors()
 {
    return [
        'file' => [
            'class' => 'trntv\filekit\behaviors\UploadBehavior',
            'filesStorage' => 'myfileStorage', // my custom fileStorage from configuration(for properly remove the file from disk)
            'multiple' => true,
            'attribute' => 'files',
            'uploadRelation' => 'uploadedFiles',
            'pathAttribute' => 'path',
            'baseUrlAttribute' => 'base_url',
            'typeAttribute' => 'type',
            'sizeAttribute' => 'size',
            'nameAttribute' => 'name',
            'orderAttribute' => 'order'
        ],
    ];
 }

对于单个文件上传

 public function behaviors()
 {
     return [
          'file' => [
              'class' => 'trntv\filekit\behaviors\UploadBehavior',
              'filesStorage' => 'fileStorageMy', // my custom fileStorage from configuration(for properly remove the file from disk)
              'attribute' => 'file',
              'pathAttribute' => 'path',
              'baseUrlAttribute' => 'base_url',
               ...
          ],
      ];
 }

在相应的类中查看附加设置

验证

您可以通过两种方式对上传执行验证。客户端验证由Blueimp 文件上传执行。有关可用的选项,请参阅文档

服务器端验证由[[yii\web\UploadAction]]执行,其中您可以配置用于验证过程的[[yii\base\DynamicModel]]的验证规则

提示

添加水印

安装 intervention/image

composer require intervention/image

编辑您的上传操作如下

public function actions(){
    return [
           'upload'=>[
               'class'=>'trntv\filekit\actions\UploadAction',
               ...
               'on afterSave' => function($event) {
                    /* @var $file \League\Flysystem\File */
                    $file = $event->file;
                    
                    // create new Intervention Image
                    $img = Intervention\Image\ImageManager::make($file->read());
                    
                    // insert watermark at bottom-right corner with 10px offset
                    $img->insert('public/watermark.png', 'bottom-right', 10, 10);
                    
                    // save image
                    $file->put($img->encode());
               }
               ...
           ]
       ];
}