zoukankan      html  css  js  c++  java
  • yii2.0图片上传

    在根目录下夹uploads文件夹
    控制器   UploadController.php
    <?php
    namespace frontendcontrollers;
    
    use Yii;
    use frontendmodelsUploadForm;
    use yiiwebUploadedFile;
    
    
    class UploadController extends yiiwebController
    {
       public function actionUpload(){
    //实例化model
    $model = new UploadForm();
    // 判断是否是POST表单提交
    if (Yii::$app->request->isPost) {

    $model->file = UploadedFile::getInstance($model,'file');
    // var_export($model->file);die;
    if($model->file->saveAs(yii::$app->basePath.'/../uploads/'.$model->file->baseName.'.'. $model->file->extension)){
    $this->redirect(['site/index']);
    }else{
    echo"上传失败";
    }
    } else {
    return $this->render('upload', ['model' => $model]);
    }

    }
    } 

    model层UploadForm.php
    <?php
    namespace frontendmodels;
    
    use yiiaseModel;
    use yiiwebUploadedFile;
    
    /**
     * 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()
        {
            return [
                [['file'],'file']
            ];
        }
    }
    view里面upload.php

    <?php
    use yiiwidgetsActiveForm;
    use yiihelpersHtml;
    ?>
    
    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
    
    <?= $form->field($model,'file')->fileInput() ?>
    
        <button>提交</button>
    
    <?php ActiveForm::end() ?>
    
    
    <?= Html::img('@web/uploads/1.jpg', ['alt' => 'My logo']) ?>
  • 相关阅读:
    Matplotlib Date Index Formatter 日期索引格式化学习
    Matplotlib 日期格式转换
    Matplotlib基础 可视化绘图 学习笔记
    Python 修饰符@用法
    Linux下基于shell脚本实现学生信息管理系统
    JavaScript的popup框
    HTML语言发展史
    CSS grid 模板
    JavaScript中的正则表达式
    position的四个属性值
  • 原文地址:https://www.cnblogs.com/Pxhphp/p/6236984.html
Copyright © 2011-2022 走看看