控制器
//单文件上传 public function actionAdd() { $model = new Day3; $res = Yii::$app->request->post(); $data = $res['Day3']; $model->img = UploadedFile::getInstance($model, 'img'); if($model->upload()) { $img = $model->img->name; $data['img']=$img; $res = Yii::$app->db->createCommand()->insert('day3',$data)->execute(); if($res) { return $this->redirect(['show']); } } return $this->render('show', ['model' => $model]); }
model
<?php namespace app\models; use Yii; use yii\base\Model; use yii\db\ActiveRecord; class Day3 extends ActiveRecord { public $user,$pwd,$img; public function rules() { return [ [['img'],'file','extensions' => 'png, jpg'], ]; } public function upload() { $this->img->saveAs('uploads/'.$this->img->baseName.'.'.$this->img->extension); return true; } }
views
<?= $form->field($model, 'img')->fileInput()->label("图片") ?>