小巫师 2018-04-03 18:43:25 4360次浏览 3条评论 2 3 0

此代码可直接拿过去用,这是一个为新手提供的demo,控制器controller,模型model,视图层view,是都有的.

1、model层

<?php 

/* 
 * 小巫专属编辑
 * IT的时代领航 | come on
 * Stick to your dream
 */ 

namespace frontend\models; 

use Yii;
use yii\base\Model;
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use yii\web\UploadedFile; 

 

class File extends Model
{
    public $imageFiles;
    

    public function rules()
    {
        return [
            ['imageFiles','required','message'=>'必须上传一张jpg格式的图片哦!']
        ];
    }
    
    public function attributeLabels() {
        return[
            'imageFiles'=>'单文件上传'
        ];
        
    } 

    public function upload()
    {
        if ($this->validate()) {
            foreach ($this->imageFiles as $file) {
                $file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
            }
            return true;
        } else {
            return false;
        }
    } 


}

2、控制器

<?php

/* 
 * 小巫专属编辑
 * IT的时代领航 | come on
 * Stick to your dream
 */
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use frontend\models\File;
use yii\db;
use yii\web\UploadedFile;


class FileController extends Controller
{
    public function actionIndex(){
        $models=new File();
        return $this->render('filee',['models'=>$models]);
    }
    public function actionAdd(){
        $model = new File();
        if (Yii::$app->request->isPost) {
            $model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
            if ($model->upload()) {
                // 文件上传成功
                return;
            }
        }


    }
}

3、视图层

<?php

/* 
 * 小巫专属编辑
 * IT的时代领航 | come on
 * Stick to your dream
 */
use yii\widgets\ActiveForm;
use yii\helpers\Html;

$form = ActiveForm::begin([
    'id' => 'login-form',
    'options' =>['enctype' => 'multipart/form-data'],
    'action'=>'?r=file/add',
    'method'=>'post',
])
?>
<?= $form->field($models, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>

 


<div class="form-group">
    <div class="col-lg-offset-1 col-lg-11">
        <?= Html::submitButton('提交', ['class' => 'btn btn-primary']) ?>
    </div>
</div>
<?php ActiveForm::end() ?>
觉得很赞
您需要登录后才可以评论。登录 | 立即注册