腾讯云cos上传核心文件调用简单注释
2018-03-08 17:05
405 查看
核心文件注释:
<?php
namespace Qcloud\Cos;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Client as GSClient;
use Guzzle\Common\Collection;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\RequestInterface;
use Qcloud\Cos\Signature;
use Qcloud\Cos\TokenListener;
class Client extends GSClient {
const VERSION = '1.1.4';
private $region; // string: region.桶服务器地
private $credentials;
private $appId; // string: application id.
private $secretId; // string: secret id.
private $secretKey; // string: secret key.
private $timeout; // int: timeout。过期时间
private $connect_timeout; // int: connect_timeout。内容过期时间
private $signature;
public function __construct($config) {
/*$config new时传入的数组,
二维数组,第一维有4个key,region,credentials,timeout,connect_timeout
region:region传入为空调用默认值,不为空使用传入值,桶服务器地
credentials:数组,里面是id,密钥,配置文件
timeout:过期时间
connect_timeout:内容过期时间
*/
$this->region = isset($config['region']) ? $config['region'] : '';
$regionmap = array('cn-east'=>'ap-shanghai',
'cn-sorth'=>'ap-guangzhou',
'cn-north'=>'ap-beijing-1',
'cn-south-2'=>'ap-guangzhou-2',
'cn-southwest'=>'ap-chengdu',
'sg'=>'ap-singapore',
'tj'=>'ap-beijing-1',
'bj'=>'ap-beijing',
'sh'=>'ap-shanghai',
'gz'=>'ap-guangzhou',
'cd'=>' ap-chengdu',
'sgp'=>'ap-singapore',);
if (array_key_exists($this->region,$regionmap))
{
$this->region = $regionmap[$this->region];
}
$this->credentials = $config['credentials'];
$this->appId = isset($config['credentials']['appId']) ? $config['credentials']['appId'] : null;
$this->secretId = $config['credentials']['secretId'];
$this->secretKey = $config['credentials']['secretKey'];
$this->token = isset($config['credentials']['token']) ? $config['credentials']['token'] : null;
$this->timeout = isset($config['timeout']) ? $config['timeout'] : 3600;
$this->connect_timeout = isset($config['connect_timeout']) ? $config['connect_timeout'] : 3600;
$this->signature = new signature($this->secretId, $this->secretKey);
parent::__construct(
'http://cos.' . $this->region . '.myqcloud.com/', // base url
array('request.options' => array('timeout' => $this->timeout, 'connect_timeout' => $this->connect_timeout),
)); // show curl verbose or not
$desc = ServiceDescription::factory(Service::getService());
$this->setDescription($desc);
$this->setUserAgent('cos-php-sdk-v5/' . Client::VERSION, true);
$this->addSubscriber(new ExceptionListener());
$this->addSubscriber(new Md5Listener($this->signature));
$this->addSubscriber(new TokenListener($this->token));
$this->addSubscriber(new SignatureListener($this->secretId, $this->secretKey));
$this->addSubscriber(new BucketStyleListener($this->appId));
// Allow for specifying bodies with file paths and file handles
$this->addSubscriber(new UploadBodyListener(array('PutObject', 'UploadPart')));
}
public function __destruct() {
}
public function __call($method, $args) {
return parent::__call(ucfirst($method), $args);
}
public function createPresignedUrl(RequestInterface $request, $expires)
{
if ($request->getClient() !== $this) {
throw new InvalidArgumentException('The request object must be associated with the client. Use the '
. '$client->get(), $client->head(), $client->post(), $client->put(), etc. methods when passing in a '
. 'request object');
}
return $this
c157
->signature->createPresignedUrl($request, $this->credentials, $expires);
}
public function getObjectUrl($bucket, $key, $expires = null, array $args = array())
{
$command = $this->getCommand('GetObject', $args + array('Bucket' => $bucket, 'Key' => $key));
if ($command->hasKey('Scheme')) {
$scheme = $command['Scheme'];
$request = $command->remove('Scheme')->prepare()->setScheme($scheme)->setPort(null);
} else {
$request = $command->prepare();
}
return $expires ? $this->createPresignedUrl($request, $expires) : $request->getUrl();
}
public function upload($bucket, $key, $body, $options = array()) {
$body = EntityBody::factory($body);
$options = Collection::fromConfig(array_change_key_case($options), array(
'min_part_size' => MultipartUpload::MIN_PART_SIZE,
'params' => $options));
if ($body->getSize() < $options['min_part_size']) {
// Perform a simple PutObject operation
$rt = $this->putObject(array(
'Bucket' => $bucket,
'Key' => $key,
'Body' => $body,
) + $options['params']);
$rt['Location'] = $rt['ObjectURL'];
unset($rt['ObjectURL']);
}
else {
$multipartUpload = new MultipartUpload($this, $body, $options['min_part_size'], array(
'Bucket' => $bucket,
'Key' => $key,
'Body' => $body,
) + $options['params']);
$rt = $multipartUpload->performUploading();
}
return $rt;
}
public function copy($bucket, $key, $copysource, $options = array()) {
$options = Collection::fromConfig(array_change_key_case($options), array(
'min_part_size' => Copy::MIN_PART_SIZE,
'params' => $options));
$sourcelistdot = explode('.',$copysource);
$sourcelistline = explode('-',$sourcelistdot[0]);
$sourcebucket = $sourcelistline[0];
$sourceappid = $sourcelistline[1];
$sourceregion = $sourcelistdot[2];
$sourcekey = substr(strstr($copysource,'/'),1);
$sourceversion = "";
$cosClient = new Client(array('region' => $sourceregion,
'credentials'=> array(
'appId' => $sourceappid,
'secretId' => $this->secretId,
'secretKey' => $this->secretKey)));
if (!key_exists('VersionId',$options['params'])) {
$sourceversion = "";
}
else{
$sourceversion = $options['params']['VersionId'];
}
$rt = $cosClient->headObject(array('Bucket'=>$sourcebucket,
'Key'=>$sourcekey,
'VersionId'=>$sourceversion));
$contentlength =$rt['ContentLength'];
if ($contentlength < $options['min_part_size']) {
return $this->copyObject(array(
'Bucket' => $bucket,
'Key' => $key,
'CopySource' => $copysource."?versionId=".$sourceversion,
) + $options['params']);
}
$copy = new Copy($this, $contentlength, $copysource."?versionId=".$sourceversion, $options['min_part_size'], array(
'Bucket' => $bucket,
'Key' => $key
) + $options['params']);
return $copy->performUploading();
}
/**
* Determines whether or not a bucket exists by name
*
* @param string $bucket The name of the bucket
* @param bool $accept403 Set to true if 403s are acceptable
* @param array $options Additional options to add to the executed command
*
* @return bool
*/
public function doesBucketExist($bucket, $accept403 = true, array $options = array())
{
try {
$this->HeadBucket(array(
'Bucket' => $bucket));
return True;
}catch (\Exception $e){
return False;
}
}
/**
* Determines whether or not an object exists by name
*
* @param string $bucket The name of the bucket
* @param string $key The key of the object
* @param array $options Additional options to add to the executed command
*
* @return bool
*/
public function doesObjectExist($bucket, $key, array $options = array())
{
try {
$this->HeadObject(array(
'Bucket' => $bucket,
'Key' => $key));
return True;
}catch (\Exception $e){
return False;
}
}
public static function encodeKey($key) {
return $key;
return str_replace('%2F', '/', rawurlencode($key));
}
public static function explodeKey($key) {
// Remove a leading slash if one is found
//return explode('/', $key && $key[0] == '/' ? substr($key, 1) : $key);
return $key;
return ltrim($key, "/");
}
}
使用调用方法:
$appid = 'id';
$bucket = '你的桶名';
$SecretId = '';
$SecretKey = '';
$path = '上传路径自定义';
$region = '桶服务器所在缩写;ap-beijing';
$cosClient = new \Qcloud\Cos\Client(array('region' => $region,
'credentials' => array(
'appId' => $appid,
'secretId' => $SecretId,
'secretKey' => $SecretKey)));
//获取bucket列表
$result = $cosClient->listBuckets();
print_r($result);
<?php
namespace Qcloud\Cos;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Client as GSClient;
use Guzzle\Common\Collection;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\RequestInterface;
use Qcloud\Cos\Signature;
use Qcloud\Cos\TokenListener;
class Client extends GSClient {
const VERSION = '1.1.4';
private $region; // string: region.桶服务器地
private $credentials;
private $appId; // string: application id.
private $secretId; // string: secret id.
private $secretKey; // string: secret key.
private $timeout; // int: timeout。过期时间
private $connect_timeout; // int: connect_timeout。内容过期时间
private $signature;
public function __construct($config) {
/*$config new时传入的数组,
二维数组,第一维有4个key,region,credentials,timeout,connect_timeout
region:region传入为空调用默认值,不为空使用传入值,桶服务器地
credentials:数组,里面是id,密钥,配置文件
timeout:过期时间
connect_timeout:内容过期时间
*/
$this->region = isset($config['region']) ? $config['region'] : '';
$regionmap = array('cn-east'=>'ap-shanghai',
'cn-sorth'=>'ap-guangzhou',
'cn-north'=>'ap-beijing-1',
'cn-south-2'=>'ap-guangzhou-2',
'cn-southwest'=>'ap-chengdu',
'sg'=>'ap-singapore',
'tj'=>'ap-beijing-1',
'bj'=>'ap-beijing',
'sh'=>'ap-shanghai',
'gz'=>'ap-guangzhou',
'cd'=>' ap-chengdu',
'sgp'=>'ap-singapore',);
if (array_key_exists($this->region,$regionmap))
{
$this->region = $regionmap[$this->region];
}
$this->credentials = $config['credentials'];
$this->appId = isset($config['credentials']['appId']) ? $config['credentials']['appId'] : null;
$this->secretId = $config['credentials']['secretId'];
$this->secretKey = $config['credentials']['secretKey'];
$this->token = isset($config['credentials']['token']) ? $config['credentials']['token'] : null;
$this->timeout = isset($config['timeout']) ? $config['timeout'] : 3600;
$this->connect_timeout = isset($config['connect_timeout']) ? $config['connect_timeout'] : 3600;
$this->signature = new signature($this->secretId, $this->secretKey);
parent::__construct(
'http://cos.' . $this->region . '.myqcloud.com/', // base url
array('request.options' => array('timeout' => $this->timeout, 'connect_timeout' => $this->connect_timeout),
)); // show curl verbose or not
$desc = ServiceDescription::factory(Service::getService());
$this->setDescription($desc);
$this->setUserAgent('cos-php-sdk-v5/' . Client::VERSION, true);
$this->addSubscriber(new ExceptionListener());
$this->addSubscriber(new Md5Listener($this->signature));
$this->addSubscriber(new TokenListener($this->token));
$this->addSubscriber(new SignatureListener($this->secretId, $this->secretKey));
$this->addSubscriber(new BucketStyleListener($this->appId));
// Allow for specifying bodies with file paths and file handles
$this->addSubscriber(new UploadBodyListener(array('PutObject', 'UploadPart')));
}
public function __destruct() {
}
public function __call($method, $args) {
return parent::__call(ucfirst($method), $args);
}
public function createPresignedUrl(RequestInterface $request, $expires)
{
if ($request->getClient() !== $this) {
throw new InvalidArgumentException('The request object must be associated with the client. Use the '
. '$client->get(), $client->head(), $client->post(), $client->put(), etc. methods when passing in a '
. 'request object');
}
return $this
c157
->signature->createPresignedUrl($request, $this->credentials, $expires);
}
public function getObjectUrl($bucket, $key, $expires = null, array $args = array())
{
$command = $this->getCommand('GetObject', $args + array('Bucket' => $bucket, 'Key' => $key));
if ($command->hasKey('Scheme')) {
$scheme = $command['Scheme'];
$request = $command->remove('Scheme')->prepare()->setScheme($scheme)->setPort(null);
} else {
$request = $command->prepare();
}
return $expires ? $this->createPresignedUrl($request, $expires) : $request->getUrl();
}
public function upload($bucket, $key, $body, $options = array()) {
$body = EntityBody::factory($body);
$options = Collection::fromConfig(array_change_key_case($options), array(
'min_part_size' => MultipartUpload::MIN_PART_SIZE,
'params' => $options));
if ($body->getSize() < $options['min_part_size']) {
// Perform a simple PutObject operation
$rt = $this->putObject(array(
'Bucket' => $bucket,
'Key' => $key,
'Body' => $body,
) + $options['params']);
$rt['Location'] = $rt['ObjectURL'];
unset($rt['ObjectURL']);
}
else {
$multipartUpload = new MultipartUpload($this, $body, $options['min_part_size'], array(
'Bucket' => $bucket,
'Key' => $key,
'Body' => $body,
) + $options['params']);
$rt = $multipartUpload->performUploading();
}
return $rt;
}
public function copy($bucket, $key, $copysource, $options = array()) {
$options = Collection::fromConfig(array_change_key_case($options), array(
'min_part_size' => Copy::MIN_PART_SIZE,
'params' => $options));
$sourcelistdot = explode('.',$copysource);
$sourcelistline = explode('-',$sourcelistdot[0]);
$sourcebucket = $sourcelistline[0];
$sourceappid = $sourcelistline[1];
$sourceregion = $sourcelistdot[2];
$sourcekey = substr(strstr($copysource,'/'),1);
$sourceversion = "";
$cosClient = new Client(array('region' => $sourceregion,
'credentials'=> array(
'appId' => $sourceappid,
'secretId' => $this->secretId,
'secretKey' => $this->secretKey)));
if (!key_exists('VersionId',$options['params'])) {
$sourceversion = "";
}
else{
$sourceversion = $options['params']['VersionId'];
}
$rt = $cosClient->headObject(array('Bucket'=>$sourcebucket,
'Key'=>$sourcekey,
'VersionId'=>$sourceversion));
$contentlength =$rt['ContentLength'];
if ($contentlength < $options['min_part_size']) {
return $this->copyObject(array(
'Bucket' => $bucket,
'Key' => $key,
'CopySource' => $copysource."?versionId=".$sourceversion,
) + $options['params']);
}
$copy = new Copy($this, $contentlength, $copysource."?versionId=".$sourceversion, $options['min_part_size'], array(
'Bucket' => $bucket,
'Key' => $key
) + $options['params']);
return $copy->performUploading();
}
/**
* Determines whether or not a bucket exists by name
*
* @param string $bucket The name of the bucket
* @param bool $accept403 Set to true if 403s are acceptable
* @param array $options Additional options to add to the executed command
*
* @return bool
*/
public function doesBucketExist($bucket, $accept403 = true, array $options = array())
{
try {
$this->HeadBucket(array(
'Bucket' => $bucket));
return True;
}catch (\Exception $e){
return False;
}
}
/**
* Determines whether or not an object exists by name
*
* @param string $bucket The name of the bucket
* @param string $key The key of the object
* @param array $options Additional options to add to the executed command
*
* @return bool
*/
public function doesObjectExist($bucket, $key, array $options = array())
{
try {
$this->HeadObject(array(
'Bucket' => $bucket,
'Key' => $key));
return True;
}catch (\Exception $e){
return False;
}
}
public static function encodeKey($key) {
return $key;
return str_replace('%2F', '/', rawurlencode($key));
}
public static function explodeKey($key) {
// Remove a leading slash if one is found
//return explode('/', $key && $key[0] == '/' ? substr($key, 1) : $key);
return $key;
return ltrim($key, "/");
}
}
使用调用方法:
$appid = 'id';
$bucket = '你的桶名';
$SecretId = '';
$SecretKey = '';
$path = '上传路径自定义';
$region = '桶服务器所在缩写;ap-beijing';
$cosClient = new \Qcloud\Cos\Client(array('region' => $region,
'credentials' => array(
'appId' => $appid,
'secretId' => $SecretId,
'secretKey' => $SecretKey)));
//获取bucket列表
$result = $cosClient->listBuckets();
print_r($result);
相关文章推荐
- [置顶] 腾讯云 对象储存java实现COS文件上传与返回的URL
- cos与EXT调用AJAX提交上传文件
- 腾讯云cos对象存储服务文件上传api就是一个大坑
- 超简单快速实现附件上传(各种格式文件)和下载显示(调用浏览器下载后选择可以打开的应用查看)
- 腾讯云上传文件,下载文件方法注释
- 上传文件(图片、视频等)至七牛云存储核心内容
- struts2中简单的文件上传
- 常用通用简单文件上传功能
- 简单的文件上传代码
- secureCRT简单上传、下载文件记录
- arm调用thumb(相同文件和不同文件)并且返回 简单小例子
- springMVC文件上传的简单配置
- JS简单实现文件上传实例代码(无需插件)
- 最简单的上传文件
- 《JavaWeb---简单应用---练习JDBC,JSTL》---上传Excel文件,利用工具包解析,将数据储存到数据库中,可以查询删除
- 简单解决 multipart/form-data 文件上传表单中 传递参数无法获取的办法! (解决办法:动态更改表单提交URL)
- 递归调用简单例子——按层次列出文件夹下所有文件和文件夹
- 简单实用H5的FormData对象上传文件
- php多文件上传-简单示例,适合初学参考。