以blob格式将图片插入db-Yii

时间:2018-07-29 16:19:17

标签: php yii

我的数据库表上还有一个名为avatar的额外列,它是一种Blob类型,我想用它来存储小头像,我更喜欢它而不是在服务器上上传文件。

这是文件上的一些代码。我对php很陌生,所以如果您能指导我将代码放在什么地方以及在哪里放置,我将不胜感激。

模型(Customer.php)

namespace app\models;

use Yii;
use yii\db\Expression;
use yii\web\IdentityInterface;
use app\helpers\StringHelper;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;

/**
 * Class Customer
 * @package app\models
 */
class Customer extends \app\models\auto\Customer implements IdentityInterface
{
const STATUS_INACTIVE = 'inactive';
const STATUS_ACTIVE = 'active';
const STATUS_DEACTIVATED = 'deactivated';

/**
 * @var string
 */
public $passwordConfirm = '';
public $passwordCurrent = '';
public $password = '';

public function rules()
{
    $rules = [
        [['email', 'first_name', 'last_name', 'phone'], 'trim'],
        [['first_name', 'last_name', 'email', 'country', 'business_type'], 'string', 'max' => 100],
        [['password'], 'string', 'length' => [6, 100]],

        [['first_name', 'last_name', 'email', 'password', 'passwordConfirm'], 'required', 'on' => self::SCENARIO_CREATE],
        [['passwordConfirm'], 'compare', 'compareAttribute' => 'password', 'on' => self::SCENARIO_CREATE],
    ];
    return $rules;
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return ArrayHelper::merge(parent::attributeLabels(), [
        'first_name'             => t('app', 'First Name'),
        'last_name'              => t('app', 'Last Name'),
        'phone'                  => t('app', 'Phone Mobile'),
        'passwordConfirm'        => t('app', 'Confirm Password'),
        'passwordCurrent'        => t('app', 'Current Password'),
    ]);
}

/**
 * @param $customer_uid
 * @return auto\Customer|array|null
 */
public function findByUid($customer_uid)
{
    return $this->find()->where(array(
        'customer_uid' => $customer_uid,
    ))->one();
}

/**
 * @return string
 */
public function generateUid()
{
    $unique = StringHelper::uniqid();
    $exists = $this->findByUid($unique);

    if (!empty($exists)) {
        return $this->generateUid();
    }

    return $unique;
}

/**
 * @return string
 */
public function getUid()
{
    return $this->customer_uid;
}


/**
 * @param int|string $customer_id
 * @return static
 */
public static function findIdentity($customer_id)
{
    return static::findOne($customer_id);
}

/**
 * @return int
 */
public function getId()
{
    return $this->customer_id;
}

控制器(AccountController.php)

namespace app\controllers;

use app\helpers\StringHelper;
use app\models\Customer;
use yii\helpers\ArrayHelper;
use yii\web\Response;
use app\yii\web\Controller;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use app\yii\filters\OwnerAccessRule;
use yii\web\UploadedFile;

/**
 * Class AccountController
 * @package app\controllers
 */
class AccountController extends Controller
{

/**
 * @return Response
 */
public function actionIndex()
{
    if (app()->customer->isGuest == true) {
        return $this->redirect(['account/login']);
    } else {
        return $this->redirect(['/']); //path to redirect after login
    }
}

/**
 * @return string|Response
 */
public function actionInfo()
{
    if (app()->customer->isGuest == true) {
        return $this->redirect(['account/index']);
    }

    $id = app()->customer->id;

    $modelAbout = $this->findModel($id);

    $modelPassword = clone $modelAbout;
    $modelPassword->scenario = 'update_password';

    $modelEmail = clone $modelAbout;
    $modelEmail->scenario = 'update_email';

    $modelCompany = CustomerStore::findOne(['customer_id' => $id]);
    if (empty($modelCompany)) {
        $modelCompany = new CustomerStore();
    }

    app()->view->title = t('app','Personal Info') . ' - ' . options()->get('app.settings.common.siteName', 'My App');

    /* render the view */

    return $this->render('info', [
        'modelAbout'    => $modelAbout,
        'modelPassword' => $modelPassword,
    ]);
}

/**
 * @return array|Response
 */
public function actionUpdateInfoAbout()
{
    if (!request()->isAjax) {
        return $this->redirect(['account/index']);
    }

    response()->format = Response::FORMAT_JSON;

    $id = app()->customer->identity->id;
    $model = Customer::findOne($id);
    $model->scenario = Customer::SCENARIO_UPDATE;

    $model->load(request()->post());

    if (!$model->save()) {
        return ['result' => 'error', 'errors' => $model->getErrors()];
    }
    return ['result' => 'success', 'msg' => t('app', 'Thanks for sharing! Your information has been updated.')];
}

}

查看(info.php)

View (Info.php)

<?php
use app\assets\AccountAsset;
use yii\bootstrap\ActiveForm;
use yii\helpers\ArrayHelper;
use app\helpers\DateTimeHelper;
use yii\helpers\Html;
use app\models\Country;
use kartik\widgets\FileInput;
use yii\helpers\Url;

AccountAsset::register($this);
?>

<div class="block-body collapse" id="about-block">
        <?php $form = ActiveForm::begin([
            'id'        => 'form-change-about',
            'method'    => 'post',
            'action'    => ['account/update-info-about'],
            'enableAjaxValidation' => false,
        ]); ?>
        <div class="row">
            <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <?= $form->field($modelAbout, 'first_name', [
                        'template'      => '{input} {error}',
                ])->textInput([ 'placeholder' => t('app','First Name'), 'class' => ''])->label(false); ?>
                </div>
            <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <?= $form->field($modelAbout, 'last_name', [
                        'template'      => '{input} {error}',
                ])->textInput([ 'placeholder' => t('app','Last Name'), 'class' => ''])->label(false); ?>
            </div>
        </div>
        </div>

        <div class="row">
            <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
                <button type="submit" id="submit-account-info-about" class="btn-as" value="Submit"><?=t('app','Submit');?></button>
            </div>
        </div>
    <?php ActiveForm::end(); ?>
</div>

希望不会有太多麻烦。找不到分步教程

0 个答案:

没有答案