引入官方 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',
'credentials' => [
'appId' => env('COS_APPID'),
'secretId' => env('COS_SECRETID'),
'secretKey' => env('COS_SECRETKEY')
]
]);
try {
$result = $cosClient->putObject([
'Bucket' => 'img-'.env('COS_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;
$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{
$url = 'http://xxxx.file.myqcloud.com'.$filename;
$url = $url;
}
}else{
return Y::error('上傳失敗2');
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結