Skip to content
关注公众号,获取新课通知

上传图片


安装文件系统扩展包(https://gitee.com/thans/thinkphp-filesystem-cloud)

composer require thans/thinkphp-filesystem-cloud

配置文件系统 config/filesystem.php

php
<?php
return [
    // 默认磁盘
    'default' => env('filesystem.driver', 'local'),
    // 磁盘列表
    'disks'   => [
        // ...
        // 更多的磁盘配置信息
        'aliyun' => [
            'type'         => 'aliyun',
            'accessId'     => '******',
            'accessSecret' => '******',
            'bucket'       => 'bucket',
            'endpoint'     => 'oss-cn-shenzhen.aliyuncs.com',
            'url'          => 'https://tangzhe123-com.oss-cn-shenzhen.aliyuncs.com',//不要斜杠结尾,此处为URL地址域名。
        ],
    ],
];

公共函数 app/common.php

php
// 上传图片
function uploadFile($key){
    try {
        $M = 1024 * 2048;
        validate([
            $key=>'fileSize:'.$M.'|fileExt:jpg,png,gif,jpeg'
        ])->check(request()->file());
        $file = request()->file($key);
        // 单图上传
        if (!is_array($file)){
            $savename = \think\facade\Filesystem::disk('aliyun')->putFile( 'demo', $file,'uniqid');
            return str_replace('\\','/',$savename);
        }
        // 多图上传
        $result = [];
        foreach ($file as $v) {
            $result[] = \think\facade\Filesystem::disk('aliyun')->putFile( 'demo', $v,'uniqid');
        }
        return $result;
    } catch (think\exception\ValidateException $e) {
        ApiException($e->getMessage());
    }
}

控制器 app/controller/admin/Image.php

php
public function save(Request $request)
{
	// 获取数据
    $file = request()->file('img');
    $classId = getValByKey('image_class_id',$request->param(),0);
    // 验证并上传图片
    $result = uploadFile('img');
    // 写入数据库
    if (!is_array($result)){  //单图上传
        $data = [
            'url'=>config('filesystem.disks.aliyun.url').'/'.$result,
            'name'=>$result,
            'path'=>$result,
            'image_class_id'=>$classId
        ];
		return showSuccess($this->M->create($data));
    }
    // 多图上传
    $data = [];
    foreach ($result as $v) {
        $data[] = [
             'url'=>config('filesystem.disks.aliyun.url').'/'.$v,
             'name'=>$v,
             'path'=>$v,
             'image_class_id'=>$classId
        ];
    }
    return showSuccess($this->M->saveAll($data));
}

验证器 app/validate/admin/Image.php

php
protected $rule = [
       // ...
       'image_class_id|相册'=>'integer|>=:0|isExist:ImageClass,false',
       // ...
   ];

protected $scene = [
   	// ...
   	'save'=>['image_class_id'],
];

路由 router/admin.php

php
Route::post('image/upload','admin.Image/save');