yii2-starter-kit/yii2-file-kit

Yii2 文件上传和存储套件

安装数: 165,059

依赖项: 12

建议者: 0

安全性: 0

星标: 156

关注者: 21

分支: 105

开放问题: 19

类型:yii2-extension

2.1.5 2020-07-20 14:38 UTC

README

GitHub Workflow Status Packagist Version (custom server) Packagist

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

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

在此处您可以查看可用的 文件系统适配器 列表

演示

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

安装

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

运行

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

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

将其添加到您的 composer.json 文件中的 require 部分。

文件存储

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

  • 其主要任务是为每个文件生成唯一的名称并触发相应的事件。
'fileStorage'=>[
    'class' => 'trntv\filekit\Storage',
    'useDirindex' => true,
    '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'],
    'uploadPath' => 'subfolder', // optional, for storing files in storage subfolder
    'sortable' => true,
    'maxFileSize' => 10 * 1024 * 1024, // 10Mb
    'minFileSize' => 1 * 1024 * 1024, // 1Mb
    'maxNumberOfFiles' => 3, // default 1,
    'acceptFileTypes' => new \yii\web\JsExpression('/(\.|\/)(gif|jpe?g|png)$/i'),
    'showPreviewFilename' => false,
    'editFilename' => false,
    'clientOptions' => [/* ...other blueimp options... */]
]);

独立使用 - 无模型

echo \trntv\filekit\widget\Upload::widget([
    'name' => 'filename',
    'hiddenInputId' => 'filename', // must for not use model
    'url' => ['upload'],
    'uploadPath' => 'subfolder', // optional, for storing files in storage subfolder
    'sortable' => true,
    'maxFileSize' => 10 * 1024 * 1024, // 10Mb
    'minFileSize' => 1 * 1024 * 1024, // 1Mb
    'maxNumberOfFiles' => 3, // default 1,
    'acceptFileTypes' => new \yii\web\JsExpression('/(\.|\/)(gif|jpe?g|png)$/i'),
    'showPreviewFilename' => false,
    'editFilename' => false,
    'clientOptions' => [/* ...other blueimp options... */]
]);

与 ActiveForm 一起使用

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

上传小部件事件

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

  • start
  • fail
  • done
  • always

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

'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 ... }'),
 ]

UploadBehavior

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

模型中的某个位置

对于多个文件

 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 File Upload 执行。有关可用选项的文档请参阅 此处

服务器端验证由 [[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());
               }
               ...
           ]
       ];
}