Yii2.0多文件上传实例说明

时间:2022-09-25 09:57:50

Yii2.0多文件上传实例说明 
Yii2.0多文件上传实例说明Yii2.0多文件上传实例说明

创建控制器formcontroller

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
namespace frontend\controllers;
use yii;
use yii\web\controller;
use frontend\models\uploadm;
use yii\web\uploadedfile;
class formcontroller extends controller{
  public function actionmyfiles(){
      $model=new uploadm();
      return $this->renderpartial('myfiles',['model'=>$model]);
  }
  public function actiongetfiles(){
    $model = new uploadm();
    if (yii::$app->request->ispost) {
      $model->imgfile = uploadedfile::getinstances($model, 'imgfile');
      if ($model->upload()) {
        // 文件上传成功
        echo '上传成功';
      }
    }
  }

创建模型uploadm.php

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
namespace frontend\models;
use yii;
use yii\base\model;
use yii\web\uploadedfile;
class uploadm extends model
{
  public $imgfile;
  public function rules(){
    return [
       [['imgfile'], 'file','maxfiles' => 5],//最多5张
    ];
  }
  public function upload()
  {
   if ($this->validate()) {
     foreach ($this->imgfile as $file) {
       $file->saveas('uploads/' . $file->basename . '.' . $file->extension);
     }
     return true;
   } else {
     return false;
   }
  }
}

创建视图/views/form/myfiles.php

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
use yii\helpers\html;
use yii\widgets\activeform;
$form = activeform::begin([
  'id' => 'login-form',
  'options' => ['class' => 'form-horizontal','enctype' => 'multipart/form-data'],
  'action'=>'?r=form/getfiles',
  'method'=>'post'
]) ?>
  <?= $form->field($model, 'imgfile[]')->fileinput(['multiple' => true]) ?>
 
  <div class="form-group">
    <div class="col-lg-offset-1 col-lg-11">
      <?= html::submitbutton('上传', ['class' => 'btn btn-primary']) ?>
    </div>
  </div>
<?php activeform::end() ?>

以上所述是小编给大家介绍的yii2.0多文件上传实例说明,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的,在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/m0_38027358/article/details/75918730