Todos os produtos
Search
Central de documentação

Object Storage Service:Append upload (PHP SDK V1)

Última atualização: Sep 24, 2026

Use a operação AppendObject para acrescentar conteúdo a objetos appendable 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 os endpoints compatíveis, consulte Regions and endpoints.

  • As credenciais de acesso neste tópico são obtidas a partir de variáveis de ambiente. Para mais informações, consulte 配置访问凭证.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como o uso de um domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Client configuration.

  • Caso o objeto de destino não exista, a operação AppendObject cria um objeto appendable.

  • Se o objeto de destino já existir:

    • Se for um objeto appendable e a posição inicial especificada for igual ao tamanho atual, os dados são acrescentados ao final do objeto.

    • Se for um objeto appendable e a posição inicial especificada for diferente do tamanho atual, o sistema retorna o erro PositionNotEqualToLength.

    • Se não for um objeto appendable, o sistema retorna o erro ObjectNotAppendable.

Permissões

Por padrão, uma conta Alibaba Cloud possui permissões totais. Já os usuários RAM e as funções RAM vinculados a essa conta não possuem nenhuma permissão por padrão. A conta Alibaba Cloud ou o administrador da conta precisa conceder as permissões de operação por meio de RAM policies ou Bucket Policy.

API

Ação

Descrição

AppendObject

oss:PutObject

Use esta operação para fazer o upload de um objeto acrescentando seu conteúdo a um objeto existente.

oss:PutObjectTagging

Esta permissão é obrigatória. Ao fazer o upload por append, especifique as tags do objeto por meio de x-oss-tagging.

Acrescentar uma string

O código a seguir demonstra como acrescentar strings de forma sequencial 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");           

Acrescentar um arquivo local

O código a seguir demonstra como acrescentar, de forma sequencial, 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 informações sobre a operação de API utilizada nos uploads por append, consulte AppendObject.