阿里云oss图片上传

发布时间 2023-05-05 11:47:13作者: 潘潘潘的博客
    /*
    * 阿里云oss图片上传
    * $img_url       文件路径
    * $aliyun_config 阿里云配置
    * @return array
    */
    public function aliyunUpload($save_path, $aliyun_config, $img_url)
    {
        // 阿里云配置
        $accessKeyId = $aliyun_config['access_key'];
        $accessKeySecret = $aliyun_config['secret_key'];
        $endpoint = $aliyun_config['endpoint'];
        $bucket= $aliyun_config['bucket'];
        if (!$accessKeyId || !$accessKeySecret || !$endpoint || !$bucket) {
            throw new \think\Exception('配置不能为空');
        }

        $file_dir = 'article/'.date('Ymdhi').'/'; // 文件路径
        $file_type = pathinfo(parse_url($save_path)['path'])['extension'];// 文件类型
        $file_name = time() . uniqid().'.'.$file_type; // 文件名
        $file_dir_name = $file_dir.$file_name;

        Db::startTrans();
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $result = $ossClient->uploadFile($bucket, $file_dir_name, $save_path);
            $data['img_yun_url'] = $result['info']['url'];
            Db::commit();
        } catch(OssException $e) {
            Db::rollback();
            $data['img_yun_url'] = $img_url;
        }
        return $data;
    }