PHP上传文件至腾讯云对象存储

493 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

一、开通腾讯云对象存储服务

点击前往腾讯云官网开通,开通后前往控制台获取 secretIdsecretKey

二、安装 PHP SDK
  1. 在你项目的 composer.json 文件中加入:
{
    "require": {
        "qcloud/cos-sdk-v5": ">=2.0"
    }
}
  1. 执行 composer install 进行安装。
三、代码实现
<?php
namespace app\api\common\controller;

use Qcloud\Cos\Client;

class Upload
{
    private $secretId = ""; // 云 API 密钥 SecretId;
    private $secretKey = ""; // 云 API 密钥 SecretKey;
    
    // 上传资源至腾讯云对象存储
    public function uploadToTencentCos()
    {
        $region = "ap-beijing";
        // 初始化
        $cosClient = new Client(array(
            'region' => $region,
            'schema' => 'http',
            'credentials'=> array(
                'secretId'  => $this->secretId,
                'secretKey' => $this->secretKey
            )
        ));
        // 接收文件
        $file = $_FILES['file'];
        // 重新命名文件
        $newName = uniqid().time().strrchr($file['name'], '.');
        // 上传资源
        $result = $cosClient->putObject(array(
            'Bucket' => '', // 你的 bucket 名称
            'Key' => $newName,
            'Body' => fopen($file['tmp_name'], 'rb'),
            'ContentType' => 'image/jpg,image/png,image/jpeg,image/tmp'
        ));
        // 查看结果
        print_r($result);
    }
}