# 处理上传文件
## 重新封装了Yii2的 UploadedFile 来处理来处理上传文件。
实例:
#### 1 Model 定义好 image 和 file 的验证规则
```php
<?php
namespace App\Model;
use ESD\Yii\Base\Model;
class UploadFileProcess extends Model
{
//Upload image file
public $image;
//Upload attachment file
public $file;
public function rules()
{
return [
[['image'], 'file', 'skipOnEmpty' => true, 'extensions' => 'jpg,jpeg,png,gif', 'checkExtensionByMimeType' => false, 'maxSize' => 2000 * 1000],
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'jpg,jpeg,png,gif,zip,rar,tar,gz,bz2,doc,docx,xls,xlsx,ppt,pptx,txt,pdf,md', 'checkExtensionByMimeType' => false, 'maxSize' => 2000 * 1000]
];
}
public function attributeLabels()
{
return [
'image' => '图片',
'file' => '文件'
];
}
}
```
> checkExtensionByMimeType:验证规则依据文件MIME 类型,还是扩展名,false标识根据扩展名验证。跟YII2规则一致。
#### 2. Controller和Action处理客户请求
```php
use ESD\Yii\Helpers\FileHelper;
use ESD\Yii\Helpers\Json;
use ESD\Yii\I18n\Formatter;
use ESD\Yii\Web\UploadedFile;
use App\Model\UploadFileProcess;
/**
* @PostMapping("post-test")
* @throws \Exception
*/
public function actionPost()
{
$fileProcessModel = new UploadFileProcess();
$uploadFile = new UploadedFile();
//设置上传保存后的相对路径
$uploadFile->setUploadBasePath(sprintf("uploads/file/%s/", date("Ymd")));
//模型属性file赋值
$fileProcessModel->file = $uploadFile->instanceByName('file');
//验证上传的文件是否符合
if (!$fileProcessModel->validate()) {
//显示报错信息,也返回客户端错误信息
var_dump($fileProcessModel->errors);
}
//文件名
$fileName = sprintf("%s.%s", $uploadFile->generateFilename(), $fileProcessModel->file->extension);
//保存文件相对路径
$filePath = $uploadFile->getUploadBasePath() . $fileName;
//保存文件物理路径
$fileSavePath = $uploadFile->getUploadSavePath() . $fileName;
//保存文件
$fileProcessModel->file->saveAs($fileSavePath, true);
//返回给浏览器的文件URL
$fileUrl = $uploadFile->getFileUrl($filePath);
$data = [
'code' => 200,
'message' => '上传成功',
'data' => [
[
'name' => $fileProcessModel->file->name,
'path' => $filePath,
'save_name' => $fileName,
'url' => $fileUrl,
'size' => $fileProcessModel->file->size,
'short_size' => (new Formatter())->asShortSize($fileProcessModel->file->size)
]
]
];
$this->response
->setHeaders([
'Content-Type' => 'application/json;charset=utf8'
])
->withContent(Json::encode($data))
->end();
}
```
Postman测试结果如下:
```json
{
"code": 200,
"message": "上传成功",
"data": [
{
"name": "sdk-0003.xlsx",
"path": "uploads/file/20210204/a6cb5f741d8a8cbf6e144907869a15b4c619dd4f.xlsx",
"save_name": "a6cb5f741d8a8cbf6e144907869a15b4c619dd4f.xlsx",
"url": "http://192.168.108.131:8080/uploads/file/20210204/a6cb5f741d8a8cbf6e144907869a15b4c619dd4f.xlsx",
"size": 8609,
"short_size": "8.41 KiB"
}
]
}
```
> 如果保存路径和返回URL不一致,重写返回URL即可。范例属于常规操作。
>
> KiB / kB,MiB / MB,GiB / GB,前者单位1024,后者单位1000。跟YII2规则一致。
>
> 如果需要KB、MB显示,则需要 Formatter->sizeFormatBase = 1000。
- 1 介绍
- 2 安装
- 2.1 环境
- 2.2 安装
- 3 配置
- 3.1 Server配置
- 3.2 端口配置
- 3.3 项目结构
- 3.4 内核优化
- 4 服务
- 4.1 HTTP服务
- 4.1.1 路由
- 4.1.1.1 静态路由
- 4.1.1.2 路由定义
- 4.1.1.3 路由方法
- 4.1.1.4 路由分组
- 4.1.1.5 资源路由
- 4.1.1.6 端口作用域
- 4.1.1.7 异常处理
- 4.1.1.8 跨域请求
- 4.1.1.9 路由缓存
- 4.1.2 控制器
- 4.1.2.1 控制器初始化
- 4.1.2.2 前置后置操作
- 4.1.2.3 跳转与重定向
- 4.1.2.4 异常处理
- 4.1.3 请求
- 4.1.3.1 请求对象
- 4.1.3.2 请求信息
- 4.1.3.3 REQUEST消息
- 4.1.3.4 RESPONSE消息
- 4.1.3.5 STREAM消息
- 4.1.3.6 URI信息
- 4.1.3.7 处理上传文件
- 4.1.3.8 验证器
- 4.2 Websocket服务
- 4.2.1 Websocket配置
- 4.2.2 Websocket路由
- 4.3 TCP服务
- 4.3.1 TCP配置
- 4.3.2 TCP路由
- 4.3.3 协程处理案例
- 5 插件
- 5.15 Yii-PDO插件
- 5.15.1 PDO 连接MySQL Mariadb
- 5.15.2 PDO连接PostgreSQL
- 5.15.3 PDO连接GreenPlum
- 5.15.4 PDO连接Oracle
- 5.15.5 PDO连接Cubrid
- 5.15.6 PDO连接SQL Server
- 6 概念
- 7. Yii- I18N国际化
- 8. 模型 Yii-Model
- 8.1 快速创建模型
- 8.2 快速创建多个模型
- 8.3 核心验证器 Core Validators
- 9. 配合数据库工作
- 9.1.数据库访问对象 Database Access Objects
- 9.2 查询构造器 Query Builder
- 9.3 活动记录 Active Record