Todos os produtos
Search
Central de documentação

Object Storage Service:Append upload (PHP SDK V1)

Última atualização: Jul 03, 2026

Chame a operação AppendObject para adicionar conteúdo a objetos anexáveis existentes.

Observações de uso

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints suportados, consulte Regiões e endpoints.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso.

  • Este exemplo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como o uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configuração do cliente.

  • Caso o objeto ao qual você deseja anexar conteúdo não exista, a operação AppendObject cria um novo objeto anexável.

  • Se o objeto de destino já existir:

    • Quando o objeto for anexável e a posição inicial especificada for igual ao tamanho atual do objeto, os dados serão adicionados ao final dele.

    • Se o objeto for anexável, mas a posição inicial definida for diferente do tamanho atual, o sistema retorna o erro PositionNotEqualToLength.

    • Para objetos que não são do tipo anexável, ocorre o erro ObjectNotAppendable.

Permissões

Por padrão, uma conta Alibaba Cloud possui permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não têm nenhuma permissão inicialmente. O administrador ou a própria conta Alibaba Cloud deve conceder as permissões operacionais necessárias por meio de políticas do RAM ou Bucket Policy.

API

Ação

Descrição

AppendObject

oss:PutObject

Utilize esta operação para fazer upload de um objeto anexando-o a um objeto existente.

oss:PutObjectTagging

Essa permissão é obrigatória quando tags de objeto são definidas via x-oss-tagging durante o upload por anexação.

Anexar uma string

O código abaixo ilustra como anexar strings sequencialmente ao arquivo srcexampleobject.txt no bucket examplebucket.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// The China (Hangzhou) endpoint is used as an example. Set the endpoint to the actual endpoint. For more information about the mapping between regions and endpoints, see Endpoints.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. For more information about bucket naming conventions, see Buckets.
$bucket= "examplebucket";
// Specify the full path of the object. Do not include the bucket name. For more information about object naming conventions, see Terms.
$object = "srcexampleobject.txt";
// Specify the strings to append in sequence. After the first, second, and third append operations, the file content is "Hello OSS", "Hi OSS", and "OSS OK", respectively.
$content_array = array('Hello OSS', 'Hi OSS', 'OSS OK');

$options = array(
    'headers' => array(
        // Specify the web page caching behavior when the object is downloaded.
        // 'Cache-Control' => 'no-cache',
        // Specify the name of the object when it is downloaded.
        // 'Content-Disposition' => 'attachment;filename=oss_download.jpg',
        // Specify the expiration time.
        // 'Expires' => 'Fri, 31 Dec 2021 16:57:01 GMT',
        // Specify whether to overwrite an object that has the same name during an append upload. Set this parameter to true to prohibit overwriting.
        // 'x-oss-forbid-overwrite' => 'true',
        // Specify the server-side encryption method for each part of the object.
        // 'x-oss-server-side-encryption'=> 'AES256',
        // Specify the encryption algorithm for the object.
        // 'x-oss-server-side-data-encryption'=>'SM4',
        // Specify the storage class of the object.
        // 'x-oss-storage-class' => 'Standard',
        // Specify the access permissions for the object.
        // 'x-oss-object-acl' => 'private',
        ),
);

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    // Perform the first append upload. The position for the first append is 0. The return value indicates the position for the next append. The position for subsequent appends is the length of the file before the append.
    $position = $ossClient->appendObject($bucket, $object, $content_array[0], 0,$options);
    $position = $ossClient->appendObject($bucket, $object, $content_array[1], $position,$options);
    $position = $ossClient->appendObject($bucket, $object, $content_array[2], $position,$options);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");           

Anexar um arquivo local

O exemplo a seguir demonstra como anexar sequencialmente o conteúdo dos arquivos locais examplefilea.txt, examplefileb.txt e examplefilec.txt ao arquivo exampleobject.txt no bucket examplebucket.

 <?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// The China (Hangzhou) endpoint is used as an example. Set the endpoint to the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name.
$bucket= "examplebucket";
// Specify the full path of the object. Do not include the bucket name.
$object = "exampleobject.txt";
// Specify the full path of the local file. If you do not specify a local path, the file is uploaded from the project path of the sample program by default.
$filePath = "D:\\localpath\\examplefilea.txt";
$filePath1 = "D:\\localpath\\examplefileb.txt";
$filePath2 = "D:\\localpath\\examplefilec.txt";

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
    // Perform the first append upload. The position for the first append is 0. The return value indicates the position for the next append. The position for subsequent appends is the length of the file before the append.
    $position = $ossClient->appendFile($bucket, $object, $filePath, 0);
    $position = $ossClient->appendFile($bucket, $object, $filePath1, $position);
    $position = $ossClient->appendFile($bucket, $object, $filePath2, $position);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");            

Referências

Para mais detalhes sobre a operação de API utilizada neste processo, consulte AppendObject.