paullzi / yii2-file-behavior
为 Yii2 提供文件存储和图片缩略图行为
v1.4.2
2020-07-09 07:12 UTC
Requires
- php: >=5.4.0
- yiisoft/yii2: ~2.0.0
- yiisoft/yii2-imagine: ~2.1.0|~2.2.0
README
为 Yii2 提供文件存储和图片缩略图行为。
功能
- ActiveRecord 的单文件和多文件存储
- 无需额外数据库字段的多图片缩略图
- 用户友好的 API
- 灵活的类继承
- 支持 Yii 别名和不同的 web/real 路径位置
安装
通过 Composer 安装
composer require paulzi/yii2-file-behavior:~1.2.0
或者
"paulzi/yii2-file-behavior" : "~1.2.0"
将以下内容添加到您的 composer.json
文件的 require
部分中。
使用方法
在模型中使用 FileBehavior 并填写属性选项
class Sample extends \yii\db\ActiveRecord { public function behaviors() { return [ [ 'class' => 'paulzi\fileBehavior\FileBehavior', 'path' => '@webroot/files', 'url' => '@web/files', 'attributes' => [ 'file' => [], 'files' => [ 'class' => 'paulzi\fileBehavior\FileMultiple', ], 'image' => [ 'class' => 'paulzi\fileBehavior\Image', 'types' => [ 'original' => [1200, 1200], 'mid' => [400, 400], 'thm' => [120, 120], ], ], 'images' => [ 'class' => 'paulzi\fileBehavior\FileMultiple', 'item' => [ 'class' => 'paulzi\fileBehavior\Image', 'types' => [ 'thm' => [120, 120], ], ] ], ], ], ]; } }
设置文件
$model = Sample::findOne(1); $file = UploadedFile::getInstance($model, 'file'); $model->file->value = $file->tempName; $model->save(); $model = Sample::findOne(2); $files = UploadedFile::getInstances($model, 'images'); foreach ($files as $file) { $model->images[] = $file->tempName; } $model->save();
获取文件
$model = Sample::findOne(1); $url = $model->file->url; $path = $model->file->path; $model = Sample::findOne(2); foreach ($model->images as $image) { echo $image->url; // original image url echo $image->thm->url; // thm image url }
删除文件
$model = Sample::findOne(1); $model->file->value = null; $model->save(); $model = Sample::findOne(1); $model->files[2]->value = null; $model->save(); $model = Sample::findOne(2); $model->images->value = null; $model->save();
图片盐
为了生成缩略图文件名,使用文件名和缩略图类型的哈希值。如果您需要防止获取不同类型的缩略图,可以通过设置包含秘密的选项来设置盐
public function behaviors() { return [ [ 'class' => 'paulzi\fileBehavior\FileBehavior', 'attributes' => [ 'image' => [ 'class' => 'paulzi\fileBehavior\Image', 'salt' => 'secret', 'types' => [ 'mid' => [400, 400], 'thm' => [120, 120], ], ], ], ], ]; }
全局设置选项
您可以通过使用 依赖注入 全局设置 salt、路径和 URL 选项
config\main.php
:
'aliases' => [ '@cdnWeb' => 'http://s.example.com', ], 'on beforeRequest' => function () { \Yii::$container->set('paulzi\fileBehavior\FileBehavior', [ 'path' => '@cdn\web\files', 'url' => '@cdnWeb\web\files', ]); \Yii::$container->set('paulzi\fileBehavior\Image', [ 'salt' => Yii::$app->params['salt'], ]); },
config\params-local.php
:
'salt' => 'secret salt',
扩展
您可以扩展类以更改路径构建函数或更改文件存储
默认情况下,文件存储在 {path}/{folder}/{12}/{12}/{1234567890abcdef1234567890ab}.{extension}