项目中使用composer引入阿里OSS

一.项目中引入composer

1.新建composer.json文件
2.添加依赖

{
    "name": "myproject",
    "type": "project",
    "require": {
        "aliyuncs/oss-sdk-php": "^2.2"
    },
    "repositories": {
        "packagist": {
            "type": "composer",
            "url": "https://packagist.phpcomposer.com"
        }
    }
}

二.核心代码中引入vendor/autoload.php

require __DIR__."/vendor/autoload.php"

三.使用oss

use OSS\OssClient;
use OSS\Core\OssException;

class OssUpload{
    private $accessKey = '';
    private $secretKey = '';
    private $endpoint = '';
    private $bucket = '';
    private $ossFileUrl = '';

    public function __construct(){
        $this->accessKey   = OSS_ACCESSKEY_ID;
        $this->secretKey   = OSS_ACCESSKEY_SECRET;
        $this->bucket      = OSS_BUCKET;
        $this->endpoint    = OSS_ENDPOINT;
    }
    
    /**
     * 上传接口
     * @DateTime  2019-05-27
     * @param string $filename 文件名
     * @param string $tempFile 临时文件
     * @throws OssException  [文件类型]
     */
    public function upload($filename, $tempFile){
        //获取对象
        $auth = new OssClient($this->accessKey, $this->secretKey, $this->endpoint);
         try {
            //上传图片
             $result  = $auth->uploadFile($this->bucket, $filename, $tempFile);
             $this->ossFileUrl = $this->cdnParseUrl($result['oss-request-url']);
             return $this->ossFileUrl;
         } catch (OssException $e) {
            return $e->getMessage();
         }
    }

    private function cdnParseUrl($url)
    {
        // 替换 url  http://xxxxxx.cn => abc.oss-us-west-1.aliyuncs.com
        return str_replace('abc.oss-us-west-1.aliyuncs.com', 'xxxxxx.cn', $url);
    }
}

你可能感兴趣的:(项目中使用composer引入阿里OSS)