weison-tech/yii2-file-kit

Yii2 文件上传和存储套件

安装: 66

依赖: 1

建议者: 0

安全: 0

星星: 0

关注者: 2

分支: 105

类型:yii2-extension

1.2.0 2017-01-12 21:30 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:03:51 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'=>[
    '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'
        ...
    ]
]

有关 flysystem 的更多信息,请参阅 http://flysystem.thephpleague.com/

使用第三方扩展

  • 创建文件系统组件(示例使用 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());
               }
               ...
           ]
       ];
}