Tous les produits
Search
Centre de documentation

Object Storage Service:Effectuer un chargement par ajout à l'aide du SDK OSS pour PHP

Dernière mise à jour :Aug 18, 2026

Vous pouvez ajouter du contenu à des objets existants de type « appendable ». Cette rubrique explique comment effectuer un chargement par ajout à l'aide du SDK Object Storage Service (OSS) pour PHP.

Notes

  • L'exemple de code de cette rubrique utilise l'ID de région cn-hangzhou de la région Chine (Hangzhou). Par défaut, un endpoint public permet d'accéder aux ressources d'un bucket. Pour accéder aux ressources du bucket depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et endpoints pris en charge, consultez la page Régions et endpoints.

  • Le chargement simple nécessite l'autorisation oss:PutObject. Pour plus d'informations, reportez-vous à la section Accorder une stratégie personnalisée.

  • Si l'objet auquel vous souhaitez ajouter du contenu n'existe pas, l'appel de cette opération crée un objet de type « appendable ».

  • Si l'objet auquel vous souhaitez ajouter du contenu existe déjà :

    • S'il s'agit d'un objet de type « appendable » et que la position spécifiée pour le début de l'ajout correspond à sa longueur actuelle, le contenu est ajouté à la fin de l'objet.

    • S'il s'agit d'un objet de type « appendable » mais que la position spécifiée pour le début de l'ajout ne correspond pas à la longueur actuelle de l'objet, l'erreur PositionNotEqualToLength est renvoyée.

    • Si l'objet n'est pas de type « appendable », l'erreur ObjectNotAppendable est renvoyée.

  • Dans cette rubrique, les identifiants d'accès sont récupérés à partir des variables d'environnement. Pour plus d'informations, consultez la page Sélection du produit.

Exemple de code

Utiliser la méthode AppendObject

<?php

// Introduce autoload files to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint for accessing OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];

// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command-line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"];       // The name of the object.

// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Specify the content that you want to append.
$data='Hello Append Object'; // Replace the sample data with your actual content.

// Create an AppendObjectRequest object to append data to a specific object.
$request = new Oss\Models\AppendObjectRequest(bucket: $bucket, key: $key);
$request->body = Oss\Utils::streamFor($data); // Specify that the HTTP request body is a binary stream.
$request->position = 0; // Set the position from which the first append operation starts to 0.

// Perform the append upload operation.
$result = $client->appendObject($request);

// Display the result.
// Display the HTTP status code and the request ID to check whether the request succeeded.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request succeeded.
    'request id:' . $result->requestId . PHP_EOL .    // The request ID, which is used to debug or trace a request.
    'next append position:' . $result->nextPosition . PHP_EOL // Specify the position from which the next append operation starts.
);

Référence

  • Pour consulter l'exemple de code complet relatif au chargement par ajout, rendez-vous sur GitHub.