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']) ?>
  • 相关阅读:
    向强大的SVG迈进
    手把手教你写个小程序定时器管理库
    蒲公英 · JELLY技术周刊 Vol.11 Lighthouse 测试报告生成
    ES6语法——let和const
    北京天地益星面经
    JS的数据类型你真的懂了吗
    北京MedPeer凉经
    flex布局语法+实例
    面试官问:你有多少种方式实现三栏布局?
    CSS粘性定位
  • 原文地址:https://www.cnblogs.com/Pxhphp/p/6236984.html
Copyright © 2011-2022 走看看