yii 的单文件上传
首先新建一个Model层,防止与现有的表单小部件的Model 冲突,然后再我们的Model里 写一个上传的方法 叫upload
另外为了验证文件的尺寸大小 我 们在model里写了一个限制文件大小的方法 checksize
如下所示
<?php /** * Created by PhpStorm. * User: administor * Date: 2017/5/11 * Time: 14:04 */ namespace frontend\models; use yii\base\Model; use yii\widgets\ActiveForm; use yii\web\UploadedFile; class Upload extends Model { public $file; public $maxsize = 1024*1024*2; public $minsize = 1024*20; public function rules(){ return[ ['file','file','maxSize'=>1024*1024*2,'minSize'=>1024*20] ]; } public function upload() { if ($this->validate()) { $this->file->saveAs('../../common/upload/' . $this->file->baseName . '.' . $this->file->extension); return true; } else { return false; } } public function checksize($size){ if($size>$this->minsize && $size<$this->maxsize){ return true; }else{ return false; } } }
接下来 是控制器层
我们使用前面的表单小部件的控制器和方法 因为有一个新的model引入 所以和前边比我们多了个引用和传值
同样的 我们在控制器里也调用了判断文件尺寸的方法 杜绝用户禁用js后引起的文件大小不符合规定
<?php /** * Created by PhpStorm. * User:administor * Date: 2017/5/10 * Time: 9:39 */ namespace frontend\controllers; use yii\web\Controller; use yii; use db; use frontend\models\Form; use frontend\models\Upload; use yii\web\UploadedFile; class LoginController extends Controller { public function actionIndex(){ $sql = 'select kid,kname from exam_tiku'; $data = yii::$app->db->createCommand($sql)->queryAll(); $arr = Form::dataarr($data); //var_dump($arr);die; $model = new Form(); $models = new Upload(); return $this->render('index',['model'=>$model,'data'=>$arr,'models'=>$models]); } public function actionAdd(){ $data = Yii::$app->request->post(); $model = new Upload(); if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, 'file'); $filesize = $model->file->size; if($model->checksize($filesize)){ if ($model->upload()) { // 文件上传成功 return; } }else{ echo "filesize is not right"; } } } } 接下来是view层
<?php /** * Created by PhpStorm. * User: administor * Date: 2017/5/10 * Time: 9:41 */ use yii\helpers\Html; use yii\widgets\ActiveForm; $form = ActiveForm::begin([ 'id' => 'login-form', 'options' => ['class' => 'form-horizontal','enctype'=>'multipart/form-data'], 'action'=>'?r=login/add', 'method'=>'post' ]) ?> <?= $form->field($model, 'name') ?> <?= $form->field($model, 'pwd')->passwordInput() ?> <?= $form->field($model, 'sex')->radioList(['0'=>'男','1'=>'女']) ?> <?= $form->field($model, 'hobby')->checkboxList(['basketball'=>'篮球','baseball'=>'棒球','swim'=>'游泳']) ?> <?= $form->field($models, 'file')->fileInput() ?> <?= $form->field($model, 'age')->dropDownList($data,['prompt' => $data[3]]) ?> <div class="form-group"> <div class="col-lg-offset-1 col-lg-11"> <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?> </div> </div> <?php ActiveForm::end() ?> 注意 文件上传需要表单添加一个
'enctype'=>'multipart/form-data'这个属性 这样 文件上传的mvc三层就搭建完成了。 我们可以实现文件上传了 并且通过改变model层文件大小的限制实现上传文件大小的控制