xujinhuai 2016-07-15 13:53:38 8943次浏览 1条评论 5 1 0
/*创建模型*/

<?php
    namespace app\models;

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

    class UploadForm extends Model
    {
        public $imageFile;

        public function rules()
        {
            return [
                [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
            ];
        }

        public function upload()
        {
            if($this->validate()){
                $this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
                return true;
            }else{
                return false;
            }
        }
    }

/*创建控制器*/

<?php
    namespace app\controllers;    //这块如果写app有错,可以试着把“app”改成当前项目的根文件夹 如:namespace frontend\controllers;

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

    public function actionUpload()
    {
        $model = new UploadForm();

        if(Yii::$app->request->post()){
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
            if($model->upload()){
                //文件上传成功
                return;
            }
        }

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

/*创建视图*/

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

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
    <?= $form->field($model, 'imageFile') ->fileInput() ?>
    <button>上传</button>
<?php ActiveForm::end() ?>


觉得很赞
  • 评论于 2016-07-28 15:52 举报

    我想知道 我在我的模型 rules里边加了message
    [['file'], 'file', 'skipOnEmpty' => false,'message'=>'请选择上传文件','extensions' => 'png, jpg',],

    为什吗在界面提示的时候还是英文Please upload a file.

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