Todos los productos
Search
Centro de documentos

Object Storage Service:Carga por anexión (PHP SDK V1)

Última actualización: Sep 03, 2026

Puede invocar la operación AppendObject para agregar contenido a objetos anexables existentes.

Notas de uso

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las regiones y endpoints compatibles, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información, consulte 配置访问凭证.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como el uso de un dominio personalizado o la autenticación con credenciales de Security Token Service (STS), consulte Client configuration.

  • Si el objeto al que desea agregar contenido no existe, la operación AppendObject crea un objeto anexable.

  • Si el objeto al que desea agregar contenido ya existe:

    • Si el objeto es anexable y la posición especificada para iniciar la operación de anexión coincide con el tamaño actual del objeto, los datos se agregan al final del mismo.

    • Si el objeto es anexable pero la posición especificada para iniciar la operación de anexión no coincide con el tamaño actual del objeto, se devuelve el error PositionNotEqualToLength.

    • Si el objeto no es anexable, se devuelve el error ObjectNotAppendable.

Permisos

De forma predeterminada, una cuenta de Alibaba Cloud tiene permisos completos. Los usuarios de RAM o los roles de RAM bajo una cuenta de Alibaba Cloud no tienen ningún permiso por defecto. La cuenta de Alibaba Cloud o el administrador de la cuenta deben otorgar los permisos de operación mediante RAM policies o Bucket Policy.

API

Action

Descripción

AppendObject

oss:PutObject

Puede invocar esta operación para cargar un objeto anexándolo a un objeto existente.

oss:PutObjectTagging

Al cargar un objeto anexándolo a uno existente, si especifica etiquetas de objeto mediante x-oss-tagging, se requiere este permiso.

Anexar una cadena

A continuación se muestra cómo anexar cadenas de forma secuencial al archivo srcexampleobject.txt en el 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 un archivo local

A continuación se muestra cómo anexar de forma secuencial el contenido de los archivos locales examplefilea.txt, examplefileb.txt y examplefilec.txt al archivo exampleobject.txt en el 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");            

Referencias

Para obtener más información sobre la operación de API utilizada para cargas por anexión, consulte AppendObject.