You need to enable JavaScript to run this app.
导航

普通上传(PHP SDK)

最近更新时间2024.02.04 18:30:58

首次发布时间2022.11.16 14:58:44

本文介绍普通上传对象的示例代码。

示例代码

普通上传使用 Psr\Http\Message\StreamInterface 作为对象的数据源,您可以通过 TosClient->putObject 实现普通上传,示例代码如下:

<?php

// 假设使用 composer 安装
require_once __DIR__ . '/vendor/autoload.php';

use Tos\TosClient;
use Tos\Exception\TosClientException;
use Tos\Exception\TosServerException;
use Tos\Model\PutObjectInput;
use Tos\Model\Enum;

$file = null;
try {
    $client = new TosClient([
        'region' => 'your region',
        'endpoint' => 'your endpoint',
        // 从环境变量中获取访问密钥
        'ak' => getenv('TOS_ACCESS_KEY'),
        'sk' => getenv('TOS_SECRET_KEY'),
    ]);
    
    // 上传字符串
    $content = 'hello world';
    $input = new PutObjectInput('bucket-test',  'key-test',  $content);
    // 设置对象 ACL
    $input->setACL(Enum::ACLPublicRead);
    // 设置对象 StorageClass
    $input->setStorageClass(Enum::StorageClassStandard);
    // 设置对象自定义元数据
    $input->setMeta(['aaa' => 'bbb', '中文键' => '中文值']);
    // 设置对象 Content-Type
    $input->setContentType('text/plain');
    $output = $client->putObject($input);
    echo $output->getRequestId() . PHP_EOL;
    
    // 上传文件流
    $input->setKey('key-test2');
    // 假设本地文件路径为 local_file_path
    $file = fopen('local_file_path', 'r');
    $input->setContent($file);
    $output = $client->putObject($input);
    echo $output->getRequestId() . PHP_EOL;
    
} catch (TosClientException $ex) {
    echo $ex->getMessage() . PHP_EOL;
} catch (TosServerException $ex) {
    echo $ex->getRequestId() . PHP_EOL;
    echo $ex->getStatusCode() . PHP_EOL;
    echo $ex->getErrorCode() . PHP_EOL;
} finally {
    if (is_resource($file)) {
        fclose($file);
    }
}