【原创】ThinkPHP5.0/5.1/6.0 腾讯云COS 上传类 腾讯云对象存储类

先安装Composer 安装方法自行百度,安装后执行下面代码

 composer require qcloud/cos-sdk-v5

新建控制器代码如下

/** 
* 腾讯云COS上传类
* @author Reaper <a@0oo.ren> 
* @request https://www.52bz.la
*/ 
namespace app\admin\controller;

class Common extends Controller
{
    /** 
    * 上传文件
    * @param file 上传文件 type上传到Cos目录
    * @return Json
    */ 
    public function uploads()
    {
        $file = request()->file('file');
        $fileInfo = $file->getInfo();
        $types = ['image'];//文件类型
        if (!in_array(explode('/', $fileInfo['type'])[0], $types)) {
            jsons(['code' => 0, 'msg' => '类型错误,不支持的文件类型', 'off' => 0]);
        }

        $filename = explode('.', $fileInfo['name']);
        $key = input('type').'/'.date('Ymd').'/'.md5(time().'https://www.52bz.la'.rand(0,9999)).'.'.end($filename);
        $bucket = '存储桶名';

        $cosClient = $this->initCos();
        $result = $cosClient->putObject([
            'Bucket' => $bucket,
            'Key' => $key,
            'Body' => fopen($fileInfo['tmp_name'], 'rb')
        ]);

        $url = '你的URL'.$key;
        json(['code' => 0, 'msg' => '上传成功', 'data' => ['src' => $url]]);
    }

    /** 
    * 配置文件
    * @return 
    */ 
    private function initCos()
    {
        $cosClient = new \Qcloud\Cos\Client([
            'region' => 'ap-guangzhou', //设置一个默认的存储桶地域
            'schema' => 'https', //协议头部,默认为http
            'credentials'=> [
                'secretId'  => SecretId,
                'secretKey' => SVLSecretKey
            ]
        ]);
        return $cosClient;
    }
}
Last modification:September 18th, 2019 at 10:09 am
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment