PHP code example of larva / flysystem-tos

1. Go to this page and download the library: Download larva/flysystem-tos 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 / flysystem-tos example snippets


use Tos\TosClient;

$client = new TosClient([
    'region' => 'cn-beijing',
    'endpoint' => 'tos-cn-beijing.volces.com',
    'ak' => 'your-access-key',
    'sk' => 'your-secret-key',
]);

use Larva\Flysystem\Tos\TOSAdapter;
use Larva\Flysystem\Tos\PortableVisibilityConverter;

$adapter = new TOSAdapter(
    client: $client,
    bucket: 'your-bucket-name',
    prefix: '',                              // 可选,存储路径前缀
    visibility: new PortableVisibilityConverter(), // 可选,可见性转换器
    mimeTypeDetector: null,                 // 可选,MIME 类型检测器
    options: []                             // 可选,额外选项
);

use League\Flysystem\Filesystem;

$filesystem = new Filesystem($adapter);

// 写入文件
$filesystem->write('path/to/file.txt', 'file contents');

// 读取文件
$contents = $filesystem->read('path/to/file.txt');

// 检查文件是否存在
$exists = $filesystem->fileExists('path/to/file.txt');

// 删除文件
$filesystem->delete('path/to/file.txt');

// 列出目录内容
foreach ($filesystem->listContents('path/to/dir') as $item) {
    echo $item->path() . PHP_EOL;
}

use Larva\Flysystem\Tos\VisibilityConverter;
use League\Flysystem\Visibility;

class CustomVisibilityConverter implements VisibilityConverter
{
    public function visibilityToAcl(string $visibility): string
    {
        return $visibility === Visibility::PUBLIC ? 'public-read' : 'private';
    }

    public function aclToVisibility(string $acl): string
    {
        return $acl === 'public-read' ? Visibility::PUBLIC : Visibility::PRIVATE;
    }

    public function defaultForDirectories(): string
    {
        return Visibility::PUBLIC;
    }
}

// AppServiceProvider::boot()
use Illuminate\Support\Facades\Storage;
use Larva\Flysystem\Tos\TOSAdapter;
use League\Flysystem\Filesystem;

Storage::extend('tos', function ($app, $config) {
    $client = new \Tos\TosClient([
        'region' => $config['region'],
        'endpoint' => $config['endpoint'],
        'ak' => $config['ak'],
        'sk' => $config['sk'],
    ]);

    $adapter = new TOSAdapter($client, $config['bucket'], $config['prefix'] ?? '');

    return new Filesystem($adapter);
});

'tos' => [
    'driver' => 'tos',
    'region' => env('TOS_REGION', 'cn-beijing'),
    'endpoint' => env('TOS_ENDPOINT', 'tos-cn-beijing.volces.com'),
    'ak' => env('TOS_AK'),
    'sk' => env('TOS_SK'),
    'bucket' => env('TOS_BUCKET'),
    'prefix' => env('TOS_PREFIX', ''),
],

Storage::disk('tos')->put('file.txt', 'contents');
$contents = Storage::disk('tos')->get('file.txt');

$client = $adapter->getClient();
$bucket = $adapter->getBucket();