sevin 2016-02-26 11:30:09 2857次浏览 2条回复 0 1 0

文件上传的时候应用的类文件找不到 复制了手册的代码居然报错 哪位大牛可以展示一下MVC层的代码~ 万分致谢!

觉得很赞
  • 回复于 2016-02-27 14:46 举报

    model层:

    <?php
        namespace app\models;
        use Yii;
        use yii\base\model;
        use yii\db\ActiveRecord;
        use yii\web\UploadedFile;
        
        class Upload extends Model {
            public $file;
            public function rules(){
                return [
                    [['file'],'file','extensions' => 'jpg, png,jpeg', 'mimeTypes' => 'image/jpeg, image/png, image/jpeg','skipOnEmpty' => false],
                ];
            }
        }
    ?>
    

    控制器层:

    public function actionLoad(){
        $upload=new Upload;
        $request=Yii::$app->request;
        if($request->isPost){
            //echo 'a';die;
            $upload->file=UploadedFile::getInstance($upload,'file');
            //print_r($upload);die;
            if($upload->file && $upload->validate()){
                $upload->file->saveAs('uploads/' . $upload->file->baseName . '.' . $upload->file->extension);
            }else{
                echo '<script>alert("格式不正确")</script>';
                die;
            }
        }
        return $this->render('upfile',['model'=>$upload]);
    }
    

    视图层:

    <?php
        use yii\helpers\Html;
        use yii\bootstrap\ActiveForm;
    ?>
    
    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
    
    <?= $form->field($model, 'file')->fileInput()->label('选择文件') ?>
    
    <button>Submit</button>
    
    <?php ActiveForm::end() ?>
    
    2 条回复
    回复于 2016-02-27 15:47 回复

    万分感谢!祝您新的一年里工作顺利、事业更上一层楼

    回复于 2016-02-27 16:06 回复

    谢谢,借你吉言!

    , 觉得很赞
  • 回复于 2016-02-28 14:23 举报

    去封装一下比较好,要不然每次用都要这样写,麻烦

您需要登录后才可以回复。登录 | 立即注册