路由:
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\facade\Route;
Route::post('goods/upload_goods', 'Goods/images');
//通过Route这个路由::post类型方式。为什么要用::静态函数呢?因为路由类文件就是用静态写的啊,在最下面的截图。第一个参数是写好后,怎么调用的。第二个参数是指向哪里的比如上面的指向Goods控制器/images方法的。用goods/upload_goods在地址栏里面写入的
控制器:
<?php
declare (strict_types = 1);//严格模式,代表举个例子,数据库中的字段必须与控制器中要使用的字段一致不然报错
namespace app\admin\controller;//这个文件在哪哥目录下。一级一级目录网上找。直到app停止了
use think\Validate;//调用验证器类文件
use think\Request;//调用请求类文件
use think\facade\View;//调用视图类文件
use think\facade\Db;//调用数据库链接类文件
use app\admin\validate\EnealValidate;//调用异常验证类文件
class Goods
{
public function images(Request $request)必须是请求类型的
{
// 接收文件上传
$file = $request->file("image");
// 设定文件上传的大小
$fileSize = 1024 * 1024 * 2;
// 存储上传失败的信息
$error = [];
// 存储上传成功的信息
$success = [];
// 循环批量验证
foreach ($file as $val) {
// 捕获异常
try {
// 验证文件大小、后缀
validate(['image' => 'fileSize:' . $fileSize . '|fileExt:jpg'])
->check(['image' => $val]);
// 上传文件
$saveName = \think\facade\Filesystem::putFile('swiper', $val);
// 将成功后的路径保存到数组中
$success[] = 'swiper/' . $saveName;
} catch (\think\exception\ValidateException $e) {
// 记录验证错误的失败信息
$error= [
'name' => $val->getOriginalName(),
'msg' => $e->getMessage()
];
}
}
// 组装返回数据的结果集
$data = [
'success' => $success,
'error' => $error
];
// 返回数据
return json([$data]);
}
}
存储图片目录结构:
config/filesystem.php文件》
<?php
return [
// 默认磁盘
'default' => env('filesystem.driver', 'public'),//默认保存到public目录下
// 磁盘列表
'disks' => [
'local' => [
'type' => 'local',
'root' => app()->getRuntimePath() . 'storage',
],
'public' => [
// 磁盘类型
'type' => 'local',
// 磁盘路径
'root' => app()->getRootPath() . 'public/storage',//public目录下的storage目录下哦啊
// 磁盘路径对应的外部URL路径
'url' => '/storage',
// 可见性
'visibility' => 'public',
],
// 更多的磁盘配置信息
],
];
postman测试:
postman的格式
static看到了不?