tp6多文件上传接口开发,整个流程+postman测试

2022-05-26 08:24:11 浏览数 (1)

路由:

代码语言:javascript复制
<?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 thinkfacadeRoute;


Route::post('goods/upload_goods', 'Goods/images');

控制器:

代码语言:javascript复制
<?php
declare (strict_types = 1);

namespace appadmincontroller;
use thinkValidate;
use thinkRequest;
use thinkfacadeView;
use thinkfacadeDb;
use appadminvalidateEnealValidate;
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 = thinkfacadeFilesystem::putFile('swiper', $val);
            // 将成功后的路径保存到数组中
            $success[] = 'swiper/' . $saveName;
        } catch (thinkexceptionValidateException $e) {
            // 记录验证错误的失败信息
            $error= [
                'name' => $val->getOriginalName(),
                'msg' => $e->getMessage()
            ];
        }
    }
    // 组装返回数据的结果集
    $data = [
        'success' => $success,
        'error' => $error
    ];
    // 返回数据
    return json([$data]);
}
}

存储图片目录结构:

config/filesystem.php文件》

代码语言:javascript复制
<?php

return [
    // 默认磁盘
    'default' => env('filesystem.driver', 'public'),
    // 磁盘列表
    'disks'   => [
        'local'  => [
            'type' => 'local',
            'root' => app()->getRuntimePath() . 'storage',
        ],
        'public' => [
            // 磁盘类型
            'type'       => 'local',
            // 磁盘路径
            'root'       => app()->getRootPath() . 'public/storage',
            // 磁盘路径对应的外部URL路径
            'url'        => '/storage',
            // 可见性
            'visibility' => 'public',
        ],
        // 更多的磁盘配置信息
    ],
];

postman测试:

0 人点赞