欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

服务器资源迁移到OSS

程序员文章站 2024-01-30 16:26:28
...

笔者公司后端做负载均衡,需要将图片服务抽离出来,正好用到阿里的oss服务
1.composer安装阿里sdk,或者手动引入
2.封装oss相关业务逻辑,简单实现
3.nginx修改配置,转发到buket,

const prefixUrl = '/web/';
    private $accessKeyId = '';
    private $accessKeySecret = '';
    private $endpoint = '';
    private $bucket = ‘’;

    public function upload($serverFilePath, $oldUrl = '')
    {
        try {
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $ossClient->uploadFile($this->bucket, 'web/' . $serverFilePath, $serverFilePath);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        if (file_exists($serverFilePath)) {
            unlink($serverFilePath);
        }
        if ($oldUrl != '') {
            if (file_exists($oldUrl)) {
                unlink($oldUrl);
            }
            $ossClient->deleteObject($this->bucket, 'web/' . $oldUrl);
        }
        return true;
    }

    public function del($serverFilePath)
    {
        try {
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $ossClient->deleteObject($this->bucket, 'web/' . $serverFilePath);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return true;
    }

    public function isExist($serverFilePath)
    {
        try {
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $ossClient->doesObjectExist($this->bucket, 'web/' . $serverFilePath);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return true;
    }
相关标签: PHP 阿里云 php