Yii 2.0 单文件上传

先创建一个(UploadForm.php)模型层

<?php
namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{
    /**
    * @var UploadedFile file attribute
    */
    public $file;

/**
    * @return array the validation rules.
    */
    public function rules()
    {
        //'skipOnEmpty' => false  验证
        //'extensions' => 'png, jpg, gif, jpeg'  上传的文件的格式
        return [
            [['file'], 'file'],
        ];
    }
}

------------------------------------------------------------------------------

控制器层 (UploadController.php)

<?php
namespace backend\controllers;

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

class UploadController extends Controller{
    function actionIndex(){
        $request = Yii::$app->request;
        $model = new UploadForm();
        if($request->isPost)
        {
            $model->file = UploadedFile::getInstance($model, 'file');

if ($model->file && $model->validate())
            {
                $r = $model->file->saveAs('./upload/' . $model->file->baseName . '.'. $model->file->extension);    //这是上传,upload文件夹要自己手动创建
                //获取上传文件的名称
                $r = $model->file;
                $image= $r->name;
                
                //添加入库
                $upload = \Yii::$app->db;
                $query = $upload->createCommand()->insert("upload",['image'=>$image]);
                if($query->execute())
                {
                    $this->redirect(array('upload/index'));
                }
            }
        }
        else
        {
            return $this->render('upload',['model' => $model]);
        }
    }
}

-----------------------------------------------------------------------------------------------------

视图层(upload.php)

<?php
use yii\widgets\ActiveForm;
use yii\helpers\Url;
?>

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>

<table class="table table-bordered table-hover definewidth m10">
<tr>
   <td class="tableleft">上传图片</td>
   <td><?= $form->field($model, 'file')->fileInput() ?></td>
</tr>

<tr>
   <td class="tableleft"></td>
   <td>
       <button type="submit" class="btn btn-primary" type="button">保存</button>
   </td>
</tr>

<?php ActiveForm::end() ?>

上一篇:springboot 服务工程,前端服务调用接口报跨域错误


下一篇:P3033 [USACO11NOV]牛的障碍Cow Steeplechase