yiioverflow/yii2-file-kit

Yii2 文件上传和存储套件

安装: 360

依赖项: 0

建议者: 0

安全: 0

星标: 3

关注者: 2

分支: 0

开放问题: 0

类型:yii2-extension

dev-master 2018-06-04 06:26 UTC

This package is auto-updated.

Last update: 2024-09-07 18:19:43 UTC


README

Dependency Status

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

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

演示 ---- 即将推出

安装

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

运行

composer require yiioverflow/yii2-file-kit  "@dev"

到您的 composer.json 文件的 require 部分。

文件存储

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

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

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

  1. 创建一个实现了 yiioverflow\filekit\filesystem\FilesystemBuilderInterface 的构建器类,并实现方法 build,该方法返回文件系统对象。示例
namespace app\components;

use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local as Adapter;
use yiioverflow\filekit\filesystem\FilesystemBuilderInterface;

class LocalFlysystemBuilder implements FilesystemBuilderInterface
{
    public $path;

    public function build()
    {
        $adapter = new Local(\Yii::getAlias($this->path));
        return new Filesystem($adapter);
    }
}

配置

'fileStorage'=>[
    ...
    'filesystem'=> [
        'class' => 'app\components\FilesystemBuilder',
        'path' => '@webroot/uploads'
        ...
    ]
]

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

然后您可以像这样使用它

$file = UploadedFile::getInstanceByName('file');
Yii::$app->fileStorage->save($file); // method will return new path inside filesystem
$files = UploadedFile::getInstancesByName('files');
Yii::$app->fileStorage->saveAll($files);
  1. 使用第三方扩展,例如 creocoder/yii2-flysystem,并在 filesystemComponent 配置中提供文件系统组件的名称
'fs' => [
    'class' => 'creocoder\flysystem\LocalFilesystem',
    'path' => '@webroot/files'
    ...
],
'fileStorage'=>[
    ...
    'filesystemComponent'=> 'fs'
],

操作

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

上传操作

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

public function actions(){
    return [
           'upload'=>[
               'class'=>'yiioverflow\filekit\actions\UploadAction',
               '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'=>'yiioverflow\filekit\actions\DeleteAction',
       ]
    ];
}

请参阅相应类中的其他设置

查看(下载)操作

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

请参阅相应类中的其他设置

上传小部件

独立使用

echo \yiioverflow\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'),
    'clientOptions' => [ ...other blueimp options... ]
]);

与 ActiveForm 一起使用

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

上传小部件事件

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

  • start
  • fail
  • done
  • always

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

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

UploadBehavior

此行为旨在在对应关系中将上传的文件保存到相应位置。

在模型中某个位置

对于多个文件

 public function behaviors()
 {
    return [
        'file' => [
            'class' => 'yiioverflow\filekit\behaviors\UploadBehavior',
            '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' => 'yiioverflow\filekit\behaviors\UploadBehavior',
              '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'=>'yiioverflow\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());
               }
               ...
           ]
       ];
}