PHP code example of larva / laravel-flysystem-cos
1. Go to this page and download the library: Download larva/laravel-flysystem-cos library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
larva / laravel-flysystem-cos example snippets
'cos' => [
'driver' => 'cos',
// 'endpoint' => env('TENCENT_COS_ENDPOINT'), // 接入点,留空即可
'region' => env('TENCENT_COS_REGION'), // 存储桶所在区域,如 ap-guangzhou
'credentials' => [ // 认证凭证
'appId' => env('TENCENT_COS_APP_ID'), // 存储桶名称后缀,如 1258464748
'secretId' => env('TENCENT_COS_SECRET_ID'),
'secretKey' => env('TENCENT_COS_SECRET_KEY'),
'token' => env('TENCENT_COS_TOKEN'), // 临时密钥时使用,可选
],
'bucket' => env('TENCENT_COS_BUCKET'), // 存储桶名称
'root' => env('COS_PREFIX'), // 存储路径前缀,可选
'url' => env('TENCENT_COS_URL'), // CDN 加速域名,可选
// 以下均可省略
'scheme' => 'https', // 协议头,默认 http
'timeout' => 3600,
'connect_timeout' => 3600,
'ip' => null,
'port' => null,
'domain' => null,
'proxy' => null,
'encrypt' => null,
],
'default' => 'cos',
use Illuminate\Support\Facades\Storage;
// 获取 COS 磁盘实例
$disk = Storage::disk('cos');
// 写入文件
$disk->put('path/to/file.txt', '文件内容');
// 读取文件
$contents = $disk->get('path/to/file.txt');
// 检查文件是否存在
$exists = $disk->exists('path/to/file.txt');
// 删除文件
$disk->delete('path/to/file.txt');
// 上传本地文件
$disk->putFile('uploads', new \Illuminate\Http\UploadedFile($path, $filename));
// 获取公共文件的访问 URL
$url = Storage::disk('cos')->url('path/to/file.jpg');
// 获取私有文件的临时访问 URL(有效期 5 分钟)
$tempUrl = Storage::disk('cos')->temporaryUrl(
'path/to/private-file.pdf',
now()->addMinutes(30)
);
$client = Storage::disk('cos')->getClient();
// 使用 COS SDK 直接操作
$result = $client->listObjects([
'Bucket' => 'your-bucket-name',
'Prefix' => 'uploads/',
]);