fabriziocaldarelli/yii2-file-upload

为 Yii2 的文件上传

安装: 512

依赖: 0

建议者: 0

安全: 0

星星: 1

关注者: 2

分支: 0

公开问题: 0

类型:yii2-extension

1.1.2 2024-06-26 22:20 UTC

This package is auto-updated.

Last update: 2024-09-26 23:05:46 UTC


README

为 Yii2 提供单文件和多文件上传处理程序

安装

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

运行以下命令之一:

php composer.phar require --prefer-dist fabriziocaldarelli/yii2-file-upload "*"

或者

"fabriziocaldarelli/yii2-file-upload": "*"

将以下内容添加到您的 composer.json 文件的 require 部分中。

配置

安装扩展后,在 config\main.php 中配置它,设置 imageBaseUrl、fileUploadBasePath 和 fileUploadBaseUrl

1) 在 config.php 中添加 fileUploader 模块

'modules' => [
    'fileUploader' => [
        'class' => 'sfmobile\fileUpload\Module',

        // Database table name to save files metadata
        'dbTableName' => 'tbl_file_upload',

        'defaultStorage' => 's3prod',

        'storages' => [
            's3prod' => [
                'class' => 'sfmobile\fileUpload\storages\S3Storage',

                's3Key' => 'PROD',
                's3Secret' => '1234567',
                's3Endpoint' => 'https://mys3',
                's3Bucket' => 'mybucket',
            ],                
            'local' => [
                'class' => 'sfmobile\fileUpload\storages\FileSystemStorage',

                'basePath' =>  '/var/www/vhosts/your_hosting/public_files',
                'baseUrl' =>  '/public_files',
            ],
        ]        
    ],
],

2) 在 config\main.php 的 bootstrap 部分中添加该模块

'bootstrap' => ['log', 'fileUploader'],

3) 应用数据库迁移

yii migrate --migrationPath=@vendor/fabriziocaldarelli/yii2-file-upload/migrations

对模型、视图和控制器的更改

建议创建一个继承自 Model 类的 ModelForm 类,并为处理文件(在这种情况下为 'photo')添加一个属性

如果您需要更新数据库中的其他字段,sync() 方法有一个最后的参数 $options,其结构如下:

@param $options 数组 [ 'filter' => [ 'andWhere' => [] ], 'saveFields' => [ '字段数组' ] ]

filter->andWhere 数据包含其他字段以匹配记录,saveFields 包含要插入/更新的键=>值字段集。

对模型的更改

<?php
namespace backend\models;

class Articles extends \yii\db\ActiveRecord
{
    public $formTabularIndex = null; // Needed for file upload with tabular form
    public $photo;  // attribute to store uploaded file

    // Load: initialize the files attached to model
    public function load($data, $formName = null)
    {
        $retLoad = parent::load($data, $formName);

        // Files metadata will be stored with refer_table=articles, section=articles, category=photo and refer_id=model.id
        \sfmobile\fileUpload\FileUploadCore::load($this->formTabularIndex, $this, 'photo', $this->id, 'articles', 'articles', 'photo');

        return $retLoad;

    }

    // Delete: added files deletion
    public function afterDelete()
    {
        parent::afterDelete();

        // When delete the model, files automatically will be deleted
        \sfmobile\fileUpload\FileUploadCore::deleteAll($this->id, 'articles', 'articles', 'photo');

    }

    // Save: after saved the model, also save the files
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        // File upload
        \sfmobile\fileUpload\FileUploadCore::sync($this, 'photo', \Yii::$app->user->identity->id, $this->id, 'articles', 'articles', 'photo');

    }

可以根据文件使用规则验证,如下所示:

 <?php
public function rules()
{
    return [
        // ...

        // minimum 2 files and maximum 5 files
        ['photo', 'file', 'minFiles' => 2, 'maxFiles' => 5 ],
    ];
}

对视图的更改

添加一个隐藏的 formSessionId 输入字段来管理(最终!)在同一网页中打开的多个浏览器标签(带有表单上传)。然后可以插入自己的文件输入小部件或使用由扩展提供的、从 KartikFileInput 派生的小部件

<div class="articles-form">

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?php \sfmobile\fileUpload\FileUploadCore::printHtmlFormSessionId(); ?>

    <?= $form->field($model, 'photo')->widget(\sfmobile\fileUpload\components\kartikFileInput\KartikFileInput::className(), [
    ]); ?>

此小部件自动配置为从模型获取验证规则。

对控制器的更改

创建和更新操作的内容与标准相同。

<?php
    public function actionCreate()
    {
        $model = new Articles();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }


        return $this->render('update', [
            'model' => $model,
        ]);
    }    

表格表单

在表格表单的情况下(同一表单内相同模型的多个实例),只需修改控制器中的操作。以下是一个示例

对控制器的更改

<?php
public function actionUpdateMultiple($ids)
{
    $models = \common\models\Articles::find()->andWhere(['id' => explode(',', $ids)])->all();

    foreach($models as $indexModel => $model)
    {
        $model->formTabularIndex = $indexModel;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
    }

    return $this->render('update-multiple', [
        'models' => $models,
    ]);
}

来自多个文件的模型

当您需要从多个文件存储多个模型时,这是正确的方法

对模型的更改 在模型中,在 load() 中您将传递一个额外的参数来识别要使用哪个 $_FILES 索引

<?php
class BannerHomeIndexForm extends \common\models\BannerHome
{
    public $fileInputIndexName = null; // Extra parameter to specify which $_FILES index to use
    public $formTabularIndex = null; // Needed for file upload with tabular form
    public $image;

    // Load: initialize the files attached to model
    public function load($data, $formName = null)
    {
        $retLoad = parent::load($data, $formName);

        // !!! ATTENTION TO LAST PARAMETER !!!!
        \sfmobile\fileUpload\FileUploadCore::load($this->formTabularIndex, $this, 'image', $this->id, 'banner_home', 'banner_home', 'image', $this->fileInputIndexName);

        return $retLoad;

    }

    // Delete: added files deletion
    public function afterDelete()
    {
        // ... as default example ...
    }

    // Save: after saved the model, also save the files
    public function afterSave($insert, $changedAttributes)
    {
        // ... as default example ...
    }

对控制器的更改 在控制器中,您将添加 fileInputIndexName 以传递获取文件数据的 $_FILES 索引

<?php
public function actionIndex()
{
    if(\Yii::$app->request->isPost)
    {
        foreach($_FILES['BannerHomeForm']['name']['image'] as $indexBanner => $n)
        {
            $model = new BannerHomeForm();

            $model->formTabularIndex = $indexBanner;
            $model->fileInputIndexName = 'BannerHomeForm[image]['.$indexBanner.']';
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
            }
        }
    }
    \sfmobile\fileUpload\FileUploadCore::destroySession();