Yii多文件上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fujian9544/article/details/88015339

1.分配

controller接收 

model验证和上传

2.控制器

public function actionUpload()
{
        $model = new UploadForm();  // 实例化上传类
        if (Yii::$app->request->isPost) {
            $model->files = UploadedFile::getInstances($model,'files');  //使用UploadedFile的getInstances方法接收多个文件

            $res = $model->upload();  //调用model里边的upload方法执行上传
            $err = $model->getErrors();  //获取错误信息

            echo "<pre>";
            print_r($res);  //打印上传结果
            print_r($err);  //打印错误信息,方便排错
            exit;


        }

        return $this->render('index',['model'=>$model]);

}

3.模型

UploadForm.php(Model)
<?php
namespace app\models;

use yii\base\Model;

class UploadForm extends Model
{
    public $files;  //用来保存文件

    public function rules(){
        return [
            [['files'],'file', 'skipOnEmpty' => false, 'extensions' => 'jpg, png, gif', 'mimeTypes'=>'image/jpeg, image/png, image/gif', 'maxSize'=>1024*1024*10, 'maxFiles'=>2],
            //设置图片的验证规则
        ];
    }

    public function upload(){
        $res = [];
        if ($this->validate()){ //调用验证方法
            $uploadpath = dirname(dirname(__FILE__)).'/web/uploads/';  //取得上传路径
            if (!file_exists($uploadpath)) {
                @mkdir($uploadpath, 0777, true);
            }
            foreach($this->files as $img){
                $ext = $img->getExtension();  //获取文件的扩展名
                $randnums = $this->getrandnums(); //生成一个随机数,为了重命名文件
                $imageName = date("YmdHis").$randnums.'.'.$ext;  // 重命名文件
                $filepath = $uploadpath.$imageName;  // 生成文件的绝对路径
                $res[] = $img->saveAs($filepath);    //上传,并保存结果
            }
        }

        return $res; //返回结果
    }

    /**
     * 生成随机数
     * @return string 随机数
     */
    protected function getrandnums()
    {
        $arr = array();
        while (count($arr) < 10) {
            $arr[] = rand(1, 10);
            $arr = array_unique($arr);
        }
        return implode("", $arr);
    }
}
?>

4.视图

<?php
use yii\widgets\ActiveForm;
?>

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>

<?= $form->field($model, 'files[]')->fileInput(['multiple'=>true]) ?>

    <button>Submit</button>

<?php ActiveForm::end() ?>

猜你喜欢

转载自blog.csdn.net/fujian9544/article/details/88015339