菜鸟CK 2016-07-16 22:07:38 6820次浏览 3条评论 14 6 0

新建 Upload.php 模型。

<?php
namespace app\models;

use yii\base\Model;

class Upload extends Model{
    public $image;
}

新建 UploadController.php 控制器。

<?php
namespace app\controllers;

use yii\web\Controller;

class UploadController extends Controller{

    public function actionUpload(){
	
    }
}

新建 upload.php 视图。

<?php
	use yii\helpers\Html;
?>

一、Upload.php 模型

  • 添加模型验证
public function rules() {
    return [
        [['image'],'file','skipOnEmpty' => false,'checkExtensionByMimeType' => false,'extensions' => 'jpg,jpeg,png']
    ];
}

更多验证请参考:http://www.yiichina.com/doc/api/2.0/yii-validators-validator

  • 模型添加上传方法
public function upload() {
    if($this->validate()){
        $this->image->saveAs('../runtime/'.$this->image->baseName.'.'.$this->image->extension);
        return true;
    } else {
        return false;
    }
}

二、upload.php 视图

  • 添加上传表单
<?=Html::beginForm('','post',['enctype' => 'multipart/form-data']);?>
    <?=Html::activeFileInput($model,'image',['class' => 'upload']);?>
    <?=Html::submitButton('提交',['class' => 'btn btn-primary']);?>
<?=Html::endForm();?>

三、UploadController.php 控制器

  • 引入UploadedFile类和Upload模型命名空间
use yii\web\UploadedFile;
use app\models\Upload;
  • 接收操作
public function actionUpload(){
    $upload = new Upload();
    if(\Yii::$app->request->isPost){
        $upload->image = UploadedFile::getInstance($upload,'image');
        if($upload->upload()){
            echo '上传成功!';
        }else{
            var_dump($upload->getErrors());
        }
    }
    return $this->render('upload',['model' => $upload]);
}

访问http://localhost/yii2/web/index.php?r=upload/upload

upload.png

选择一张图片,上传成功!runtime 目录下也存在了刚才上传的图片。

觉得很赞
您需要登录后才可以评论。登录 | 立即注册