fredyns / yii2-attachments
用于文件上传和模型附加的扩展
1.1.1
2021-03-19 17:23 UTC
Requires
- php: >=5.4.0
- creocoder/yii2-flysystem: ^1.0
- himiklab/yii2-colorbox-widget: *
- kartik-v/yii2-widget-fileinput: ~1.0.0
- league/flysystem-aws-s3-v3: ~1.0
- yiisoft/yii2: ~2.0.0
Requires (Dev)
- phpunit/dbunit: ~1.0
- phpunit/phpunit: ~4.0
This package is auto-updated.
Last update: 2024-09-21 15:56:34 UTC
README
将模型附件上传到 Flysystem
演示
您可以在 krajee 网站上查看上传输入的演示
安装
-
安装 yii2-flysystem 和您选择的文件系统。
请仔细查看其文档进行安装。(可能有一些更新)
-
安装此扩展的首选方式是通过 composer。
运行以下命令之一
php composer.phar require fredyns/yii2-attachments "dev-master"
或添加
"fredyns/yii2-attachments": "dev-master"
到您的
composer.json
文件的 require 部分。 -
将模块添加到
common/config/main.php
(高级模板)对于基本应用,您应该将其添加到
config/web.php
和config/console.php
中。'modules' => [ ... 'attachments' => [ 'class' => fredyns\attachments\Module::class, 'rules' => [ // Rules according to the FileValidator 'maxFiles' => 10, // Allow to upload maximum 3 files, default to 3 'mimeTypes' => 'image/png', // Only png images 'maxSize' => 1024 * 1024 // 1 MB ], 'tableName' => '{{%attachments}}' // Optional, default to 'attach_file' 'filesystem' => 'awss3Fs' // you can change though ] ... ]
-
应用迁移
'controllerMap' => [ ... 'migrate' => [ 'class' => 'yii\console\controllers\MigrateController', 'migrationNamespaces' => [ 'fredyns\attachments\migrations', ], ], ... ],
php yii migrate/up
-
将附加行为附加到您的模型(确保您的模型有 "id" 属性)
public function behaviors() { return [ ... 'fileBehavior' => [ 'class' => \fredyns\attachments\behaviors\FileBehavior::class, ] ... ]; }
-
确保您已将
'enctype' => 'multipart/form-data'
添加到 ActiveForm 选项中 -
确保您已在模块规则中指定
maxFiles
并在AttachmentsInput
上指定maxFileCount
为您想要的数字
使用方法
-
在您的模型的
form.php
中添加文件输入<?= \fredyns\attachments\components\AttachmentsInput::widget([ 'id' => 'file-input', // Optional 'model' => $model, 'options' => [ // Options of the Kartik's FileInput widget 'multiple' => true, // If you want to allow multiple upload, default to false ], 'pluginOptions' => [ // Plugin options of the Kartik's FileInput widget 'maxFileCount' => 10 // Client max files ] ]) ?>
-
在
view.php
中使用小部件显示模型的全部附件<?= \fredyns\attachments\components\AttachmentsTable::widget([ 'model' => $model, 'showDeleteButton' => false, // Optional. Default value is true ])?>
-
您可以通过调用
$model->files
来获取所有附加文件,例如foreach ($model->files as $file) { echo $file->path; }
使用事件
您可以将以下函数添加到您的模型中
public function init(){ $this->on(\fredyns\attachments\behaviors\FileBehavior::EVENT_AFTER_ATTACH_FILES, function ($event) { /** @var $files \fredyns\attachments\models\File[] */ $files = $event->files; //your custom code }); parent::init(); }