php上传文件至腾讯COS

最近初学php,看了一遍教程就开始撸代码,途中不断入坑,硬着头皮一个一个查。。。

PS:本人主要写前端,php小白,不喜勿喷,大神请绕道。。。

这不今天要写文件上传,由于前端要对接微信小程序,于是乎选择了腾讯的COS,一看文档一头雾水,不懂?那就顺着文档一步一步来。

第一步 开发准备

SDK 获取

1. GitHub
#在GitHub中获取代码
https://github.com/tencentyun/cos-php-sdk-v5

将源代码放入您的项目目录下即可使用

2. Composer

在项目目录下,新建一个composer.json的文件,内容如下

#利用Composer下载
{
    "require": {
        "qcloud/cos-sdk-v5": ">=1.0"
    }
}

然后使用下面的命令进行安装:

composer install

好啦,第一步完成,还算简单。。。

第二步 快速入门

可参照 Demo 程序,详见 GitHub 链接 。

配置文件

#这里请填写cos-autoloader.php该文件所在的相对路径
require(__DIR__ . DIRECTORY_SEPARATOR . 'cos-autoloader.php');

$cosClient = new Qcloud\Cos\Client(array('region' => getenv('COS_REGION'),
    'credentials'=> array(
        'secretId'    => getenv('COS_KEY'),
        'secretKey' => getenv('COS_SECRET'))));

看到这里我就一脸懵逼,本来就不知道配置文件放哪,网上找了半天也不知道从哪入手,后来自己摸索,终于被自己啃出来。。。

在application里面找到配置文件config.php,添加如下代码,其中:region是你的COS所属地区,secretId和secretKey在你的API秘钥管理里面都可以找到。


然后在你的controller中引入cos,就可以直接在你的函数中使用啦~

 
  
use Qcloud\Cos\Client
/**
* 上传图片到腾讯云图片服务器
*/
public function upload () {
$cosClient = new Client( config( 'tengxunyun'));
$file = request()-> file( 'file');
if ( $file) {
try {
$result = $cosClient-> putObject(
[
'Bucket' => "bucket_name",
'Key' => date( "Y-m-d") . "/" . md5( microtime()) . '.jpg',
'Body' => fopen( $file-> getInfo()[ 'tmp_name'], 'rb'),
"ACL" => "public-read-write",
// "ContentType" => "image/jpeg"
]
);
return json(
[
"code" => 0,
"msg" => '上传成功',
"data" => [
"src" => str_replace( "cos.ap-beijing", "picbj", $result[ 'ObjectURL']),
"title" => ""
]
]
);
} catch (\ Exception $e) {
return json(
[
"code" => 1,
"msg" => $e,
"data" => [
"src" => "",
"title" => ""
]
]
);
}
}
}

另外,官方提供了很多种上传文件及下载文件的方法,可以按需引用

上传文件

  • 使用 putObject 接口上传文件(最大 5GB);
  • 使用 Upload 接口分块上传文件。
# 上传文件
## putObject(上传接口,最大支持上传5G文件)
### 上传内存中的字符串
try {
    $result = $cosClient->putObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Body' => 'Hello World!'));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

### 上传文件流
try {
    $result = $cosClient->putObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Body' => fopen($local_path, 'rb')));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

### 设置header和meta
try {
    $result = $cosClient->putObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Body' => fopen($local_path, 'rb'),
        'ACL' => 'string',
        'CacheControl' => 'string',
        'ContentDisposition' => 'string',
        'ContentEncoding' => 'string',
        'ContentLanguage' => 'string',
        'ContentLength' => integer,
        'ContentType' => 'string',
        'Expires' => 'mixed type: string (date format)|int (unix timestamp)|\DateTime',
        'GrantFullControl' => 'string',
        'GrantRead' => 'string',
        'GrantWrite' => 'string',
        'Metadata' => array(
            'string' => 'string',
        ),
        'StorageClass' => 'string'));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

## Upload(高级上传接口,默认使用分块上传最大支持50T)
### 上传内存中的字符串
try {
    $result = $cosClient->Upload(
        $bucket = $bucket,
        $key = $key,
        $body = 'Hello World!');
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

### 上传文件流
try {
    $result = $cosClient->Upload(
        $bucket = $bucket,
        $key = $key,
        $body = fopen($local_path, 'rb'));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

### 设置header和meta
try {
    $result = $cosClient->upload(
        $bucket= $bucket,
        $key = $key,
        $body = fopen($local_path, 'rb'),
        $options = array(
            'ACL' => 'string',
            'CacheControl' => 'string',
            'ContentDisposition' => 'string',
            'ContentEncoding' => 'string',
            'ContentLanguage' => 'string',
            'ContentLength' => integer,
            'ContentType' => 'string',
            'Expires' => 'mixed type: string (date format)|int (unix timestamp)|\DateTime',
            'GrantFullControl' => 'string',
            'GrantRead' => 'string',
            'GrantWrite' => 'string',
            'Metadata' => array(
                'string' => 'string',
            ),
            'StorageClass' => 'string'));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

下载文件

  • 使用 getObject 接口下载文件;
  • 使用 getObjectUrl 接口获取文件下载 URL。
# 下载文件
## getObject(下载文件)
### 下载到内存
try {
    $result = $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key));
    echo($result['Body']);
} catch (\Exception $e) {
    echo "$e\n";
}

### 下载到本地
try {
    $result = $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'SaveAs' => $local_path));
} catch (\Exception $e) {
    echo "$e\n";
}

### 指定下载范围
/*
 * Range 字段格式为 'bytes=a-b'
 */
try {
    $result = $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Range' => 'bytes=0-10',
        'SaveAs' => $local_path));
} catch (\Exception $e) {
    echo "$e\n";
}

### 设置返回header
try {
    $result = $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'ResponseCacheControl' => 'string',
        'ResponseContentDisposition' => 'string',
        'ResponseContentEncoding' => 'string',
        'ResponseContentLanguage' => 'string',
        'ResponseContentType' => 'string',
        'ResponseExpires' => 'mixed type: string (date format)|int (unix timestamp)|\DateTime',
        'SaveAs' => $local_path));
} catch (\Exception $e) {
    echo "$e\n";
}

## getObjectUrl(获取文件UrL)
try {
    $url = "/{$key}";
    $request = $cosClient->get($url);
    $signedUrl = $cosClient->getObjectUrl($bucket, $key, '+10 minutes');
    echo ($signedUrl);

} catch (\Exception $e) {
    echo "$e\n";
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值