本文实例讲述了yii2框架实现表单中上传单个文件的方法。分享给大家供大家参考,具体如下:

有些时候我们提交的表单中含有文件。怎么样让表单里的数据和文件一起提交。

我的数据表tb_user内容如下:

create table `tb_user` (
 `id` int(11) unsigned not null auto_increment comment '用户id',
 `name` varchar(32) default '' comment '用户名',
 `pwd` varchar(64) default '' comment '密码',
 `head_img` varchar(256) default '' comment '图像',
 `sex` tinyint(1) default '0' comment '性别(0:男,1:女)',
 `age` tinyint(3) default '0' comment '年龄',
 primary key (`id`)
) engine=innodb default charset=utf8mb4 comment='用户表';

表单页面代码如下(至于为什么没有用activeform来创建,这个就不解释了):

<?php
use yii\helpers\url;
?>
<!doctype html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <title>表单提交</title>
</head>
<body>
<form action="<?php echo url::toroute('index/index'); ?>" method="post" enctype="multipart/form-data">
  姓名:<input type="text" name="name"><br>
  密码:<input type="password" name="pwd"><br>
  性别:<input type="radio" name="sex" value="0" checked>男
     <input type="radio" name="sex" value="1">女<br>
  年龄:<input type="number" name="age"><br>
  头像:<input type="file" name="head_img"><br>
  <input type="submit" value="提交">
  <input name="_csrf" type="hidden" value="<?php echo \yii::$app->request->csrftoken; ?>">
</form>
</body>
</html>

模型类代码如下:

<?php

namespace app\models;

use yii\db\activerecord;
use yii\web\uploadedfile;

class myuser extends activerecord
{
  //注意这里的上传路径是相对你入口文件
  const upload_paht = 'uploads/';

  //返回你要操作的数据表名
  public static function tablename()
  {
    return '{{%user}}';
  }

  //设置规则,验证表单数据
  public function rules()
  {
    return [
      ['name', 'required', 'message' => '请填写用户名'],
      ['pwd', 'string', 'length' => [6, 12], 'message' => '密码6-12位'],
      ['sex', 'in', 'range' => [0, 1], 'message' => '正确选择性别'],
      ['age', 'integer', 'min' => 1, 'max' => 120, 'message' => '正确填写年龄'],
      ['head_img', 'image', 'extensions' => ['png', 'jpg', 'gif'], 'maxsize' => 1024 * 1024 * 1024, 'message' => '请上传头像'],
    ];
  }

  //上传头像
  public function uploadheadimg()
  {
    //'head_img'这个字符串必须跟你表单中file控件的name字段相同
    $head_img = uploadedfile::getinstancebyname('head_img');
    if (!empty($head_img)) {
      $filepath = self::upload_paht . date('ymd') . '/';
      //判断文件上传路径,如果不存在,则创建
      if (!file_exists($filepath)) {
        @mkdir($filepath, 0777, true);
        @chmod($filepath, 0777);
      }
      //文件名,我们通过md5文件名加上扩展名
      $filename = md5($head_img->basename) . '.' . $head_img->extension;
      $file = $filepath . $filename;
      //保存文件到我们的服务器上
      $head_img->saveas($file);
      //返回服务器上的文件地址
      return $file;
    } else {
      return false;
    }
  }
}

控制器代码如下:

<?php

namespace app\controllers;

use yii;
use yii\web\controller;

class indexcontroller extends controller
{
  public function actionindex()
  {
    if (yii::$app->request->ispost) {
      $user = new \app\models\myuser();

      //把post过来的数据加载到user对象
      $data = yii::$app->request->post();
      //注意第二个参数设为'',默认yii的activeform创建的表单元素会加上下标
      $user->load($data, '');

      if ($user->validate()) {
        $user->pwd = yii::$app->security->generatepasswordhash($user->pwd);
        $user->head_img = $user->uploadheadimg();

        //这里保存时设为false不验证,因为pwd加密了
        $user->save(false);
      } else {
        var_dump($user->errors);
      }
    } else {
      return $this->renderpartial('index');
    }
  }
}

这样我们就可以通过表单上传图像了。