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

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).

    打赏 评论
  • dongweihuan8832 2018-11-02 10:27

    I think issue is in your file input in your form, you are not rendering it correctly based on your models rules, please try this:

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

    instead of

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

    Then test

    In your Model please try this

        $this->cv = UploadedFile::getInstances($this, 'cv');
        $this->cv = count($this->cv) > 0 ? $this->cv[0] : NULL;
        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;
        }
    

    And if you want to see what is returning from these variables above, you can add this line after this code above:

        echo "<pre>"; print_r($this->cv);print_r($user);die;
    

    This will show you data inside of $this->cv and $user

    Also please check the path you are entering should upload to that directory, so I think you are using Yii2 advance so your upload path should work like common/uploads/ instead of using ../../

    打赏 评论

相关推荐 更多相似问题