在Yii2中自动创建文件夹并上传图像

时间:2016-10-08 05:07:57

标签: yii2 yii2-advanced-app

我创建了td

这是我..\frontend\web\uploads配置中的Create函数:

PropertiesControllers.php

public function actionCreate() { $model = new Properties(); $date = date('YmdHis'); if ($model->load(Yii::$app->request->post())) { $file = \yii\web\UploadedFile::getInstance($model, 'url_img'); if (!empty($file)) $model->url_img = $date.$file; if($model->save()) { if (!empty($file)) $file->saveAs( Yii::getAlias('@frontend') .'/web/uploads/'.$date.$file); return $this->redirect(['view', 'id' => $model->id]); } return $this->render('create', ['model' => $model]); } else { return $this->render('create', ['model' => $model]); } } 存在时,它有效。但我想将uploads中的新文件夹重定向到uploads

uploads\img

它显示错误,因为if (!empty($file)) $file->saveAs( Yii::getAlias('@frontend') .'/web/uploads/img'.$date.$file); 不存在。

我不知道解决这个问题。救救我!

1 个答案:

答案 0 :(得分:3)

我建议您在img之前创建$file->saveAs(文件夹。在Yii2中,您可以使用yii\helpers\FileHelper来创建目录。如果您的问题就像img文件夹在上传内部不存在,那么您可以创建yii\helpers\FileHelper

的文件夹
$path = Yii::getAlias('@frontend')."/web/uploads/img";
\yii\helpers\FileHelper::createDirectory($path, $mode = 0775, $recursive = true);

完整代码

public function actionCreate() {

        $model = new Properties();

        $date = date('YmdHis');

        if ($model->load(Yii::$app->request->post())) {
            $file = \yii\web\UploadedFile::getInstance($model, 'url_img');
            if (!empty($file))
                $model->url_img = $date . $file;

            if ($model->save()) {   


                if (!empty($file)) {
                    $path = Yii::getAlias('@frontend') . "/web/uploads/img";
                    //here you create the folder
                    if (\yii\helpers\FileHelper::createDirectory($path, $mode = 0775, $recursive = true)) {
                        $file->saveAs(Yii::getAlias('@frontend') . '/web/uploads/img/' . $date . $file);
                    }
                }    

                return $this->redirect(['view', 'id' => $model->id]);
            }
            return $this->render('create', ['model' => $model]);
        } else {
            return $this->render('create', ['model' => $model]);
        }
    }

有关FileHelper http://www.yiiframework.com/doc-2.0/yii-helpers-filehelper.html

的更多信息