啦啦啦啦一朵花 2017-09-21 12:19:00 6143次浏览 1条评论 0 4 0

1.创建Model类 UploadForm.php

<?php 
namespace app\models;

use yii\base\Model;

class UploadForm extends Model
{

    public $imageFile;

    //制定规则
    public function rules()
    {
        return [
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }
    
    //上传
    public function upload()
    {
        $this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
        return true;
    }
}

2.在web目录下创建uploads文件夹

3.创建控制器

<?php 
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;

class IndexController extends Controller{

	//上传方法
	public function actionUpload()
	{
		//实例化上传model类
		$model = new UploadForm();
		
		if(Yii::$app->request->isPost){
			//取出model中的图片信息
			$model->imageFile = UploadedFile::getInstance($model,'imageFile');

			if($model->upload()){
				//上传成功添加入库
				$img = $model->imageFile->name;

				//添加入库
				$res = Yii::$app->db->createCommand()->insert('photo',['img'=>$img])->execute();
				
				//判断是否上传成功
				if($res){
					return $this->redirect(['list']);
				}
				return $this->goBack();
			}
		}

		return $this->render('index', ['model' => $model]);
	}
}

4.视图

<?php
use yii\widgets\ActiveForm;
?>
<h2>上传图片</h2>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>

    <?= $form->field($model, 'imageFile')->fileInput(['class'=>'btn'])->label("上传") ?>

    <button class="btn">上传</button>

<?php ActiveForm::end() ?>
觉得很赞
您需要登录后才可以评论。登录 | 立即注册