Yii2.0多文件上传实例说明
程序员文章站
2024-03-11 19:38:49
创建控制器formcontroller
创建控制器formcontroller
<?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
<?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
<?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多文件上传实例说明,希望对大家有所帮助
下一篇: Mybatis的入门示例代码