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

我的数据表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');
}
}
}

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

YII2表单中上传单个文件的更多相关文章

  1. MVC认知路【点点滴滴支离破碎】【五】----form表单上传单个文件

    //个人理解:前台一个form加input[type='file'],在加一个submit的按钮 主要设置form的action,method,enctype='multipart/form-data ...

  2. js实现上传单个文件

    js上传文件:js 上传单个文件(任意大小) 疯狂代码 http://www.CrazyCoder.cn/ :http:/www.CrazyCoder.cn/Javascript/Article832 ...

  3. Yii2表单提交(带文件上传)

    今天写一个php的表单提交接口,除了基本的字符串数据,还带文件上传,不用说前端form标签内应该有这些属性 <form enctype="multipart/form-data&quo ...

  4. input文件上传(上传单个文件/多选文件/文件夹、拖拽上传、分片上传)

    //上传单个/多个文件 <input title="点击选择文件" id="h5Input1" multiple="" accept= ...

  5. Spring Mvc:用MultiPartFile上传单个文件,多个文件

    1.单个文件上传步骤: 添加Apache文件上传jar包 首先需要下载两个apache上传文件的jar包,commons-fileupload-1.3.1jar,commons-io-2.4.jar ...

  6. 基于Spring MVC实现基于form表单上传Excel文件,批量导入数据

    在pom.xml中引入: <!--处理2003 excel--> <dependency> <groupId>org.apache.poi</groupId& ...

  7. plupload如何限制上传文件数量,限制只能上传单个文件

    1 完整代码 $(function() { $("#uploader").pluploadQueue({ runtimes : 'html5,gears,flash,silverl ...

  8. antd实战:表单上传,文件列表的过滤与限制。

    用表单上传组件最痛苦的地方是: 他的诸多行为与纯上传组件不一样,而表单的文档关于这一块基本上没有提,只能自己试. 比如我想做一个上传前的拦截. beforeUpload: (file, fileLis ...

  9. 〖Linux〗上传单个文件到FTP的Shell命令行(函数)

    #!/bin/bash - #=============================================================================== # # F ...

随机推荐

  1. select min from 连接

    预先准备 create table p( name ) ); insert into p values('黄伟福'); insert into p values('赵洪'); insert into ...

  2. 【369】列表/字典的分拆, unpacking

    参考: python--参数列表的分拆 参考: List Comprehensions 当你要传递的参数已经是一个列表,调用的函数却接受分开一个个的参数,这个时候可以考虑参数列表拆分: 可以使用* 操 ...

  3. Android DevArt4:IntentFilter学习及深入~问题描述:在不指定具体action前提下,如果有两个以上的Activity,具有完全相同的intent-filter,项目同步是否会出现异常?程序运行是否会崩溃?

    概述:GitHub IntentFilter意图过滤器,三种匹配规则:action.category.data 重点:过滤规则中必须设置 '<category android:name=&quo ...

  4. JAVAWEB 一一 Spirng(AOP面向切面)

    applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <!-- < ...

  5. effective C++学习三(仅供个人学习记录,本文摘录effective C++)

    条款 3:尽量用 new 和 delete 而不用 malloc 和 free  把 new和 delete 与malloc 和 free 混在一起用也是个坏想法.对一个用 new 获取来的指针调用 ...

  6. tensorflow serving 中 No module named tensorflow_serving.apis,找不到predict_pb2问题

    最近在学习tensorflow serving,但是运行官网例子,不使用bazel时,发现运行mnist_client.py的时候出错, 在api文件中也没找到predict_pb2,因此,后面在网上 ...

  7. Java文件上传:Restful接口接收上传文件,缓存在本地

    接口代码 import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; i ...

  8. SPSS-相关分析

    相关分析(二元定距变量的相关分析.二元定序变量的相关分析.偏相关分析和距离相关分析) 定义:衡量事物之间,或称变量之间线性关系相关程度的强弱并用适当的统计指标表示出来,这个过程就是相关分析 变量之间的 ...

  9. oracle 日志恢复数据

    1:首先查找redo,如果redo有可供恢复的信息,就那redo中的信息进行恢复,此时一般在恢复时,类似如下:SQL> recover database;Media recovery compl ...

  10. Java多线程及线程状态转换

    以下内容整理自:http://blog.csdn.net/wtyvhreal/article/details/44176369 线程:是指进程中的一个执行流程.  线程与进程的区别:每个进程都需要操作 ...