How to create a directory inside a directory in yii2 and upload file into that directory

11,474

Solution 1

In yii2, you can use 'yii\helpers\FileHelper' to create folders.

FileHelper::createDirectory($path, $mode = 0775, $recursive = true);

In your case:

public function upload()
{
    if ($this->validate()) {
        $path = 'uploads/'. USERNAMEHERE .'/'. date('YMD');
        FileHelper::createDirectory($path);
        $this->user_image->saveAs($path .'/'. $this->user_image->baseName . '.' . $this->user_image->extension);
        return true;
    } else {
        return false;
    }
}

Solution 2

Step 1:

Use 'yii\helpers\FileHelper' in your model file.

Step 2:

In the model file where you are writing the save file function, add these lines:

if ($this->validate()) {
    $path = 'uploads/'. USERNAMEHERE .'/'. date('YMD');
    FileHelper::createDirectory($path);
    $this->user_image->saveAs($path .'/'. $this->user_image->baseName . '.' . $this->user_image->extension);
    return true;
}
Share:
11,474
rji rji
Author by

rji rji

Updated on June 18, 2022

Comments

  • rji rji
    rji rji almost 2 years

    I have a form

      <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
     <?php echo $form->field($userformmodel, 'user_image')->fileInput(); ?>
     <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
     <?php ActiveForm::end(); ?>
    

    I am uploading a file in the form and submit

    In the model I have written the code as
    
     public function rules()
    {
        return [
            [['user_image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg']
        ];
    }
    
     public function upload()
    {
        if ($this->validate()) {
            $this->user_image->saveAs('uploads/' . $this->user_image->baseName . '.' . $this->user_image->extension);
            return true;
        } else {
            return false;
        }
    }
    

    In my controller

     public function actionProfile()
    {
     $model = new UserProfile();
     $userformmodel = new UserForm();
     $model->user_image = UploadedFile::getInstance($userformmodel, 'user_image');
     if($model->save(false))
                    {
                    $model->upload();        
                    }
     }
    

    This is just creating a directory called uploads. But I want to create a directory inside uploads directory for each user i.e, based upon the primary key in database table user I want to create and name the directory name.

    Example, if the user registering is saved as primarykey 4, then a directory with name 4 must be created and the file he uploads must be saved into that directory.

    How to make this happen? please help.