Yii2学习笔记(七):文件上传Upload

2022-01-10 10:38:56 浏览数 (2)

三个文件:模型、控制器和视图

1、模型:upload.PHP

  1. <?php
  2. namespace appmodels;
  3. use yiibaseModel;
  4. class Upload extends Model
  5. {
  6. public $file;
  7. /**
  8. * @return array the validation rules.
  9. */
  10. public function rules()
  11. {
  12. return [
  13. [['file'], 'file'],
  14. ];
  15. }
  16. }
  17. ?>

2、控制器:upload方法

  1. //文件上传功能
  2. public function actionUpload()
  3. {
  4. $model = new Upload();
  5. if (Yii::$app->request->isPost) {
  6. model->file = UploadedFile::getInstance(
  7.         if ($model->file && $model->validate()) {    
  8. model->file->saveAs('../uploads/' .
  9. }
  10. }
  11. return this->render('upload', ['model' =>
  12. }

3、视图:upload.php

  1. <?php
  2. use yiiwidgetsActiveForm;
  3. ?>
  4. <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
  5. <?=
  6. <button>Submit</button>
  7. <?php ActiveForm::end() ?>

0 人点赞