承接 fabriziocaldarelli/yii2-file-upload 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

fabriziocaldarelli/yii2-file-upload

Composer 安装命令:

composer require fabriziocaldarelli/yii2-file-upload

包简介

File upload for Yii2

README 文档

README

Single and Multiple file upload handler for Yii2

Installation

The preferred way to install this extension is through composer.

Either run

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

or add

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

to the require section of your composer.json file.

Configuration

Once the extension is installed, configure it in config\main.php setting imageBaseUrl, fileUploadBasePath and fileUploadBaseUrl :

1) Add fileUploader module to config.php

'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) Add the module in bootstrap section of config\main.php

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

3) Apply database migration

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

Changes to Model, View and Controller

I suggest to create ModelForm class that extends Model class and add an attribute to handle files (in this case, 'photo')

If you need to update other fields on database, sync() method has a last parameter $options that has this structure:

@param $options array of [ 'filter' => [ 'andWhere' => [] ], 'saveFields' => [ 'array of fields' ] ]

filter->andWhere data contains other field to match the record, saveFields contains set of key=>value fields to insert/update.

Changes to Model

<?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');

    }

It can be used rules validation base on file, such as:

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

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

Changes to View

Add an formSessionId hidden input field to manage (eventually!) multiple browser tabs opened in same web page (with form upload). Then can insert your own file input widget or use that provided by the extension, derived from 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(), [
    ]); ?>

This widget is automatically configure to get validation rules from Model.

Changes to Controller

Create and Update actions content is the same of standard.

<?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,
        ]);
    }    

Tabular form

In case of tabular form (multiple instances of same Model inside the same form), only the action inside the controller has to be modified. Here an example:

Changes to Controller

<?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,
    ]);
}

Models from multiple files

When you need to store multiple models from multiple files, this is the right approach:

Changes to Model Inside the model, in load() you will pass an extra parameter to identify which $_FILES index to use

<?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 ...
    }

Changes to Controller In Controller, you will add fileInputIndexName to pass index of $_FILES where get file data

<?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();

fabriziocaldarelli/yii2-file-upload 适用场景与选型建议

fabriziocaldarelli/yii2-file-upload 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 720 次下载、GitHub Stars 达 2, 最近一次更新时间为 2018 年 08 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「file」 「upload」 「extension」 「yii2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 fabriziocaldarelli/yii2-file-upload 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 fabriziocaldarelli/yii2-file-upload 我们能提供哪些服务?
定制开发 / 二次开发

基于 fabriziocaldarelli/yii2-file-upload 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 720
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-08-10