duanpuqi9965 2018-11-02 10:11
浏览 61
已采纳

YII2 - 在注册时添加上传文件

I tried add another field to signup view :

****** frontend/view/signup.php

<?php $form = ActiveForm::begin(['action' => ['site/signup'],'options' => ['method' => 'post', 'enctype' => 'multipart/form-data']]); ?>

                <?= $form->field($signup, 'email')->textInput(['autofocus' => true, 'data-constraints'=>"@Required @Email"]) ?>

                <?= $form->field($signup, 'name')->textInput(['data-constraints'=>"@Required"])->label('Imię') ?>

                <?= $form->field($signup, 'surname')->textInput(['data-constraints'=>"@Required"])->label('Nazwisko') ?>

                <?= $form->field($signup, 'phone')->textInput(['data-constraints'=>"@Required"])->label('Telefon') ?>

                <?= $form->field($signup, 'password')->passwordInput(['data-constraints'=>"@Required"])->label('Hasło') ?>

                <?= $form->field($signup, 'password_repeat')->passwordInput(['data-constraints'=>"@Required"])->label('Powtórz Hasło') ?>

                <?= $form->field($signup, 'cv')->fileInput()->label('Photo') ?>

                <div class="form-group">
                    <?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
                    <?= yii\authclient\widgets\AuthChoice::widget([
                        'baseAuthUrl' => ['site/auth'],
                        'popupMode' => false,
                        'options' => [
                                'class' => 'btn'
                        ]
                    ]) ?>
                </div>

            <?php ActiveForm::end(); ?>

Then in SignupForm.php i tried assign Instance of file to $cv and i have something like this:

******** frontend/models/SignupForm.php

class SignupForm extends Model
{
    public $email;
    public $name;
    public $surname;
    public $phone;
    public $cv;
    public $password;
    public $password_repeat;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],

            ['name', 'required'],
            ['surname', 'required'],
            ['phone', 'required'],

            [['cv'], 'file', 'extensions' => 'png, jpg'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],
            ['password_repeat', 'required'],
            ['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords do not match" ],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }
        $user = new User();
        $user->email = $this->email;
        $user->name = $this->name;
        $user->surname = $this->surname;
        $user->phone = $this->phone;

       $path = '../../common/uploads/' . $this->email . '/'; 
    $this->cv = UploadedFile::getInstanceByName('cv');
    if (!is_null($this->cv) || !empty($this->cv)){
        FileHelper::createDirectory($path);
        $this->cv->saveAs($path . $this->cv->baseName . '.' . $this->cv->extension);
        $user->cv = $this->cv->baseName . '.' . $this->cv->extension;
    }
        $user->password_reset_token = $user->generatePasswordResetToken();
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->save();

        $auth_assign = new AuthAssignment();
        $auth_assign->item_name = 'worker';
        $auth_assign->user_id = $user->getId();
        $auth_assign->save();
        return $user;
    }
}

Ok so now is action my controller :

******* frontend/controllers/SiteController.php

public function actionSignup()
    {

        $signup = new SignupForm();
        if ($signup->load(Yii::$app->request->post())) {

            if ($user = $signup->signup()) {
                if (Yii::$app->getUser()->login($user)) {

                    return $this->goHome();
                }
            }
            else {

                return $this->redirect('site/sign#undefined2');
            }
        }
    }

PROBLEM:

I always getting $cv = NULL while trying upload the file. I know CV shouldn't be an image file but this is only test that my solution works, but unfortunetly not... To ahead of questions - the file is an image with correct format "png or jpg" as it described in model rules. guys where i am wrong ? Please correct me.

  • 写回答

2条回答 默认 最新

  • doulan1073 2018-11-02 12:58
    关注

    Thanks to @Rajender Verma. Finally i get my own solution but i think his is also great. For future and others :

    frontend/views/signup.php

     <?php $form = ActiveForm::begin(['action' => ['site/signup'],'options' => ['method' => 'post', 'enctype' => 'multipart/form-data']]); ?>
    
                    <?= $form->field($signup, 'email')->textInput(['autofocus' => true, 'data-constraints'=>"@Required @Email"]) ?>
    
                    <?= $form->field($signup, 'name')->textInput(['data-constraints'=>"@Required"])->label('Imię') ?>
    
                    <?= $form->field($signup, 'surname')->textInput(['data-constraints'=>"@Required"])->label('Nazwisko') ?>
    
                    <?= $form->field($signup, 'phone')->textInput(['data-constraints'=>"@Required"])->label('Telefon') ?>
    
                    <?= $form->field($signup, 'password')->passwordInput(['data-constraints'=>"@Required"])->label('Hasło') ?>
    
                    <?= $form->field($signup, 'password_repeat')->passwordInput(['data-constraints'=>"@Required"])->label('Powtórz Hasło') ?>
    
                    <?= $form->field($signup, 'cv')->fileInput()->label('CV') ?>
    
                    <div class="form-group">
                        <?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
                        <?= yii\authclient\widgets\AuthChoice::widget([
                            'baseAuthUrl' => ['site/auth'],
                            'popupMode' => false,
                            'options' => [
                                    'class' => 'btn'
                            ]
                        ]) ?>
                    </div>
    
                <?php ActiveForm::end(); ?>
    

    then i used getInstance in SignupForm model :

    frontend/models/SignupForm.php

     public function signup()
        {
            if (!$this->validate()) {
                return null;
            }
            $user = new User();
    
            $path = \Yii::getAlias('@common') . '/uploads/' . $this->email;
            $file = UploadedFile::getInstance($this,'cv');
            if ($file instanceof UploadedFile){
                FileHelper::createDirectory($path);
                $file->saveAs($path . '/' . $file->baseName . '.' . $file->extension);
                $user->cv = $file->baseName . '.' . $file->extension;
            }
            $user->email = $this->email;
            $user->name = $this->name;
            $user->surname = $this->surname;
            $user->phone = $this->phone;
            $user->password_reset_token = $user->generatePasswordResetToken();
            $user->setPassword($this->password);
            $user->generateAuthKey();
            $user->save();
    
            $auth_assign = new AuthAssignment();
            $auth_assign->item_name = 'worker';
            $auth_assign->user_id = $user->getId();
            $auth_assign->save(false);
            return $user;
        }
    

    and my controller haven't been changed.

    As long as if($file instanceof UploadedFile) determine that $file must be an instance of UploadedFile class you can also use it for update in future (just in case you looking for that).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站