Yii How Create Dir Folder For Uploaded File?

Hello, i have some problem…

I can create dir for my upload file.

My actionCreate TASK:


    public function actionCreate() {

        $model = new Task;


        if (isset($_POST['Task'])) {

            $model->attributes = $_POST['Task'];


            $uploadedFile = CUploadedFile::getInstance($model, 'image');

            $fileName = date('Y-m-d') . '_' . $model->image;  // $timestamp + file name


            if (!is_dir(Yii::app()->basePath . '/../protected/upload/' . $model->project->id . '/' . $model->id)) {

                mkdir(Yii::app()->basePath . '/../protected/upload/' . $model->project->id . '/' . $model->id);

            }

            if ($model->save()) {

                $uploadedFile->saveAs(Yii::app()->basePath . '/../protected/upload/' . $model->project->id . '/' .  $fileName);

            }

            $this->redirect(array('view', 'id' => $model->id));

        }


        $this->render('create', array(

            'model' => $model,

        ));

    }

but, my create folder : protected/upload/[project_id]/

I need something that : protected/upload/[project_id]/[task_id]/ my file upload ->name:2013_03_26_name

He can’t see $model->id <-[task_id]

First thing…

I will never put the files uploaded by users into protected folder, it’s better to have a folder outside protected folder.

I’m not sure, but try to create the folder after the model has been saved:




if ($model->save()) {

    if (!is_dir(Yii::app()->basePath . '/../protected/upload/' . $model->project->id . '/' . $model->id)) {

        mkdir(Yii::app()->basePath . '/../protected/upload/' . $model->project->id . '/' . $model->id);

    }


    $uploadedFile->saveAs(Yii::app()->basePath . '/../protected/upload/' . $model->project->id . '/' .  $fileName);

}



Saludos!

I think you have to make sure the underlying structure also exists, so perhaps you should set the $recursive parameter of the mkdir to true. Also, you create a new instance of the model Task. If that model is an ActiveRecord model and the id parameter is your primary key, it will be empty unless you save it first (there will not be a Task ID)

(edit: I posted almost the same code as menxaca already mentioned, you probably have to save first or load your Task first.)





//$model = new Task(); //not this

//but this:

$model = Task::model()->findByPk($id);

//then $model->id will be available.

//or this:

$model = new Task();

//$model->id will be empty

$model->save();

//$model->id will be filled




You could use a transaction and roll it back if the upload failed, and you want to undo the saving of your model with :




$transaction = Yii::app()-db->beginTransaction();

try 

{

    //application logic (save model & store file, throw exception when it fails)

    $transaction->commit() //will not be reached if exception occurs

} catch (Exception $e) {

    $transaction->rollback();

}