Laravel 腾讯云 Cos 对象存储 sdk 使用示例 上传图片
引入官方 sdk
"qcloud/cos-sdk-v5": "2.*"
使用 sdk
<?php
namespace App\Service;
use Qcloud\Cos\Api;
use Illuminate\Support\Facades\Log;
class Cos {
public static function uploadImg($fileName, $realPath)
{
$cosClient = new \Qcloud\Cos\Client([
'region' => 'tj', // 华北-tj | 华南->gz | 华中->sh
'credentials' => [
'appId' => env('COS_APPID'),
'secretId' => env('COS_SECRETID'),
'secretKey' => env('COS_SECRETKEY')
]
]);
try {
$result = $cosClient->putObject([
'Bucket' => 'img-'.env('COS_APPID'), // 存储桶-appid
'Key' => $fileName, // 键名==文件名
'Body' => fopen($realPath, 'rb'), // 图片
'ServerSideEncryption' => 'AES256' // 加密
]);
return $result['Location'];
} catch (\Exception $e) {
Log::error('cos exception:'.$e->getMessage());
return false;
}
}
}
进行上传
// ----------上传图片-----------
if( $request->hasFile('img') )
{
$file = $request->file('img'); // 接受图片
if( $file->isValid() ){
// 上传成功
$ext = $file->getClientOriginalExtension(); // 扩展名
$allow = ['jpg', 'gif', 'png', 'jpeg']; // 支持的类型
if( !in_array($ext, $allow) ){
return Y::error('不支持的图片类型,请上传JPG|GIF|PNG|JPEG格式图片。');
}
// 判断大小
$size = $file->getSize();
$size = $size/1024/1024;
if($size > 3){
return Y::error('上传的图片不能超过3M');
}
// 进行上传
$realPath = $file->getRealPath(); // 文件的绝对路径
$filename = '/chat_img/'.date('Ymd').'/'.date('Ymdhis').'-'.mt_rand(100,999).'.'.$ext; // 定义文件名
// 腾讯 cos 存储
$url = Cos::uploadImg($filename, $realPath);
if( $url == false ){
// 如果发生失败 可以选择本地存储 如果不希望本地存储 删除这段代码
$disk = Storage::disk('public');
$res = $disk->put($filename, file_get_contents($realPath)); // 本地存储
if( !$res ){
return Y::error('上传失败local');
}
$url = $disk->url($filename);
}else{
// 拼接 cdn 加速地址
$url = 'http://xxxx.file.myqcloud.com'.$filename;
// 或者直接使用原链接
}
}else{
return Y::error('上传失败2');
}
本作品采用《CC 协议》,转载必须注明作者和本文链接