Karp

Aws 非公开桶资源 PHP sdk 解决方案
Aws 非公开桶读取图片解决方案.下面方法算是歪招, 正常方式请求时加入一些身份请求头, 就可以获取桶资源. 但比...
扫描右侧二维码阅读全文
04
2022/01

Aws 非公开桶资源 PHP sdk 解决方案

Aws 非公开桶读取图片解决方案.
下面方法算是歪招, 正常方式请求时加入一些身份请求头, 就可以获取桶资源. 但比较麻烦也没有php 的现成sdk.
aws 提供getObject 方法可以将非公开资源下载到本地, 需要对外输出展示位base64

   /**
     * 获取base64 图片格式
     * @throws \Exception
     */
    public function getBase64Img()
    {
        $config = AwsOss::AWS_OSS_PUBLIC_CONFIG; // aws 配置

        $url = 'http://static.xxxx.com/xxx.jpg'; // 需要转换的图片资源

        echo self::getBase64File($url, $config), PHP_EOL;
    }

    /**
     * 获取二进制加密文件
     * @param $url
     * @param array $config aws 桶配置
     * @return string
     * @throws \Exception
     */
    public static function getBase64File($url, array $config):string
    {
        $bucket = $config['bucket'];
        $sdKParams = $config['sdk_params'];

        $fileKey = trim(parse_url($url)['path'], '/'); // 一定不能带 / 桶路径

        $s3Client = new S3Client($sdKParams);
        // 下载文件资源
        $result = $s3Client->getObject(['Bucket' => $bucket, 'Key' => $fileKey]);

        $fileSourceObj = $result['Body'] ?? "";
        if ('' === $fileSourceObj) {
            throw new \Exception('文件资源拉取失败');
        }

        $type = getimagesizefromstring($fileSourceObj)['mime']; //获取二进制流图片格式

        return 'data:' . $type . ';base64,' . chunk_split(base64_encode($fileSourceObj));
    }
最后修改:2022 年 01 月 04 日 03 : 44 PM

发表评论