fredyns/yii2-attachments

用于文件上传和模型附加的扩展

安装: 36

依赖: 0

建议者: 0

安全: 0

星标: 2

关注者: 1

分支: 0

开放问题: 0

类型:yii2-extension

1.1.1 2021-03-19 17:23 UTC

This package is auto-updated.

Last update: 2024-09-21 15:56:34 UTC


README

Latest Stable Version License Total Downloads

将模型附件上传到 Flysystem

演示

您可以在 krajee 网站上查看上传输入的演示

安装

  1. 安装 yii2-flysystem 和您选择的文件系统。

    请仔细查看其文档进行安装。(可能有一些更新)

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

    运行以下命令之一

    php composer.phar require fredyns/yii2-attachments "dev-master"
    

    或添加

    "fredyns/yii2-attachments": "dev-master"
    

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

  3. 将模块添加到 common/config/main.php(高级模板)

    对于基本应用,您应该将其添加到 config/web.phpconfig/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
    	]
    	...
    ]
  4. 应用迁移

    	'controllerMap' => [
    	...
    	'migrate' => [
    		'class' => 'yii\console\controllers\MigrateController',
    		'migrationNamespaces' => [
    			'fredyns\attachments\migrations',
    		],
    	],
    	...
    	],
    php yii migrate/up
    
  5. 将附加行为附加到您的模型(确保您的模型有 "id" 属性)

    public function behaviors()
    {
    	return [
    		...
    		'fileBehavior' => [
    			'class' => \fredyns\attachments\behaviors\FileBehavior::class,
    		]
    		...
    	];
    }
  6. 确保您已将 'enctype' => 'multipart/form-data' 添加到 ActiveForm 选项中

  7. 确保您已在模块规则中指定 maxFiles 并在 AttachmentsInput 上指定 maxFileCount 为您想要的数字

使用方法

  1. 在您的模型的 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
    	]
    ]) ?>
  2. view.php 中使用小部件显示模型的全部附件

    <?= \fredyns\attachments\components\AttachmentsTable::widget([
    	'model' => $model,
    	'showDeleteButton' => false, // Optional. Default value is true
    ])?>
  3. 您可以通过调用 $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();
}