我创建了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);
不存在。
我不知道解决这个问题。救救我!
答案 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
的更多信息