xzf158
- xzf158 2017-04-20 已签到连续签到1天,获得了5个金钱
我也遇到同样的问题,处理方法如下:
namespace app\models; use Yii; use yii\db\ActiveRecord; class Page extends ActiveRecord { public function rules() { return [ [['title', 'img_url'], 'required'], [['img_url'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'], //这里是关键 skipOnEmpty 设为true ]; } public function upload() { if ($this->validate()) { $file_path = 'uploads/' . time() . $this->img_url->extension; $this->img_url->saveAs($file_path); return $file_path; } else { return false; } } }
action里写法
public function actionIndex() { $model = new Page(); if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) { $model->img_url = UploadedFile::getInstance($model, 'img_url'); $file_path = $model->upload(); if ($file_path !== false) { $model->img_url = $file_path; $model->add_date = time(); // 文件上传成功 if ($model->save()) { $this->redirect(array('step/show', 'id' => $model->id)); } } } return $this->render('index', [ 'model' => $model, ]); }