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

rji rji picture rji rji · Apr 13, 2016 · Viewed 10.7k times · Source

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.

Answer

Xiaosong Guo picture Xiaosong Guo · Apr 14, 2016

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;
    }
}