jerray/qcloud-cos-php-sdk

Tencentyun COS PHP SDK

0.5.0 2016-04-20 03:57 UTC

This package is not auto-updated.

Last update: 2024-05-08 21:57:53 UTC


README

腾讯云对象存储服务 COS PHP SDK

Latest Stable Version Total Downloads Latest Unstable Version License Build Status Coverage Status

安装

composer require jerray/qcloud-cos-php-sdk

使用方法

创建客户端实例

创建SDK客户端实例。$options中的参数请到腾讯云对象存储的密钥管理页面获取。

$options = [
    'appId' => 'Your app id',
    'secretId' => 'Your secret id',
    'secretKey' => 'Your secret key',
];
$cos = new jerray\QCloudCos\QCloudCos($options);

各接口返回结果详情参见腾讯云对象存储服务 RESTful API文档

文件操作

完整上传

$localFilePath = '/path/to/a/local/file';
$bucketName = 'bucket';
$cosFilePath = '/remote/file/path';
$bizAttr = 'File attributes';

try {
    $response = $cos->upload($localFilePath, $bucketName, $cosFilePath, $bizAttr);
    $code = $response->code;
    $fileUrl = $response->data->access_url;
} catch (jerray\QCloudCos\Exceptions\RequestException $e) {
    $response = $e->getBody();
    $httpMessage = $e->getMessage();
    $httpCode = $e->getCode();
} catch (Exception $e) {
    // ...
}

分片上传(超过一定大小的文件需要使用分片上传)

// response为最后一片的响应,与完整上传结构相同
$response = $cos->uploadSlice($localFilePath, $bucketName, $cosFilePath, $bizAttr);

查询文件

$response = $cos->queryFile($bucketName, $cosFilePath);

更新文件bizAttr

$response = $cos->updateFile($bucketName, $cosFilePath, $bizAttr);

删除文件

$response = $cos->deleteFile($bucketName, $cosFilePath);

下载文件

$result = $cos->downloadFile($bucketName, $cosFilePath, $localFilePath);

目录操作

创建目录

$response = $cos->createFolder($bucketName, 'test/');

目录列表

$limit = 20; // 每页列表数量
$pattern = 'both'; // 显示所有文件和目录 file - 只显示文件;foler - 只显示目录

// direction参数需要配合context参数使用
// context为空时始终取第一页,第一页返回的数据中会含有context参数
// 将此context值传入再次调用,即取到第二页
// direction用来控制翻页方向,next下一页,prev前一页
$context = '';
$direction = 'next';

// 取到第一页 返回当前context为第一页
$response = $cos->listFolder($bucketName, 'test/', $limit, $pattern, $context, $direction);

// next 向后翻页,取到第二页,返回当前context为第二页
$response = $cos->listFolder($bucketName, 'test/', $limit, $pattern, $response->data->context, 'next');

// prev 向前翻页,取到第一页,返回当前context为第一页
$response = $cos->listFolder($bucketName, 'test/', $limit, $pattern, $response->data->context, 'prev');

更新目录bizAttr

$response = $cos->updateFolder($bucketName, 'test/');

目录查询

$response = $cos->queryFolder($bucketName, 'test/');

删除目录

注意:目录不为空时会删除失败并抛出 jerray\QCloudCos\Exceptions\ClientException 异常

$response = $cos->deleteFolder($bucketName, 'test/');

Exceptions

接口请求异常

接口返回4xx错误时,抛出 jerray\QCloudCos\Exceptions\ClientException。 返回5xx错误时, 抛出 jerray\QCloudCos\Exceptions\ServerException。 这两个异常均继承自 jerray\QCloudCos\Exceptions\RequestException

运行时异常

涉及到本地文件读取的接口,如果本地文件不存在或读取失败,会抛出 jerray\QCloudCos\Exceptions\FileNotFoundException。 创建实例时,如果传入的自定义存储(参数store,可选参数)没有实现 jerray\QCloudCos\Contracts\Store 接口, 抛出 jerray\QCloudCos\Exceptions\InvalidStoreInstance 。 这两个异常均继承自 jerray\QCloudCos\Exceptions\RuntimeException

License

MIT