Cette rubrique explique comment télécharger des objets dans un bucket pour lequel la gestion des versions est activée.
Précautions
Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus de détails sur les régions et endpoints pris en charge, consultez Régions et endpoints.
Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Créer un OssClient.
Pour télécharger un objet, vous devez disposer de l'autorisation
oss:PutObject. Pour plus d'informations, consultez Accorder des autorisations personnalisées à un utilisateur RAM.
Téléchargement simple
Pour un bucket dont la gestion des versions est activée, OSS génère une chaîne aléatoire globalement unique servant d'ID de version pour chaque objet nouvellement téléchargé. Cet ID est renvoyé dans le champ x-oss-version-id de l'en-tête de réponse.
Pour un bucket dont la gestion des versions est suspendue, OSS attribue un ID de version « null » à chaque objet nouvellement téléchargé. Si vous téléchargez un objet portant le même nom, le nouvel objet écrase le précédent. Cela signifie que l'objet ne possède qu'une seule version, dont l'ID est « null ».
Le code suivant montre comment effectuer un téléchargement simple :
<?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 running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// The Endpoint of the China (Hangzhou) region is used as an example. Replace it with the actual Endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name. Example: example/test.txt.
$object = "<yourObjectName>";
$content = "hello world";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
try {
// Upload an object to a versioned bucket.
$ret = $ossClient->putObject($bucket, $object, $content);
// View the version information of the object.
print("versionId:" .$ret[OssClient::OSS_HEADER_VERSION_ID]);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
Pour plus d'informations sur les téléchargements simples, consultez PutObject.
Téléchargement par ajout
Lorsque vous ajoutez des données à un objet (AppendObject) dans un bucket gérant les versions, tenez compte des points suivants :
Vous ne pouvez exécuter l'opération AppendObject que sur un objet dont la version actuelle est de type Ajoutable.
Vous ne pouvez pas exécuter l'opération AppendObject sur un objet dont la version actuelle n'est pas de type Ajoutable, comme un objet normal ou un marqueur de suppression. Vous ne pouvez pas non plus effectuer cette opération si seules les versions historiques de l'objet sont de type Ajoutable.
Lorsque vous exécutez l'opération AppendObject sur un objet dont la version actuelle est de type Ajoutable, OSS ne crée pas de version historique pour cet objet.
Lorsque vous exécutez une opération PutObject ou DeleteObject sur un objet dont la version actuelle est de type Ajoutable, OSS enregistre l'objet ajoutable en tant que version historique. Vous ne pouvez plus ajouter de données à cet objet.
Le code suivant montre comment effectuer un téléchargement par ajout :
<?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 running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// The Endpoint of the China (Hangzhou) region is used as an example. Replace it with the actual Endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
$object = "<yourObjectName>";
// After the first, second, and third append uploads, the file content is "Hello OSS", "Hi OSS", and "OSS OK" respectively.
$content_array = array('Hello OSS', 'Hi OSS', 'OSS OK');
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// The first append upload. The position for the first append is 0. The return value is 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);
$position = $ossClient->appendObject($bucket, $object, $content_array[1], $position);
$position = $ossClient->appendObject($bucket, $object, $content_array[2], $position);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
Pour plus d'informations sur les téléchargements par ajout, consultez AppendObject.
Téléchargement en plusieurs parties
Dans un bucket gérant les versions, vous pouvez appeler l'opération CompleteMultipartUpload pour finaliser un téléchargement en plusieurs parties. OSS génère un ID de version unique pour l'objet entier et le renvoie dans le champ x-oss-version-id de l'en-tête de réponse.
Le code suivant montre comment effectuer un téléchargement en plusieurs parties :
<?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;
use OSS\Core\OssUtil;
// Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// The Endpoint of the China (Hangzhou) region is used as an example. Replace it with the actual Endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
$object = "<yourObjectName>";
// Specify the full path of the local file.
$uploadFile = "<yourLocalFile>";
/**
* Step 1: Initialize a multipart upload event and obtain the uploadId.
*/
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// The uploadId is returned. The uploadId is the unique identifier of the multipart upload event. You can use the uploadId to perform related operations, such as aborting or querying the multipart upload.
$uploadId = $ossClient->initiateMultipartUpload($bucket, $object);
} catch(OssException $e) {
printf(__FUNCTION__ . ": initiateMultipartUpload FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": initiateMultipartUpload OK" . "\n");
/*
* Step 2: Upload parts.
*/
$partSize = 10 * 1024 * 1024;
$uploadFileSize = sprintf('%u',filesize($uploadFile));
$pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
$responseUploadPart = array();
$uploadPosition = 0;
$isCheckMd5 = true;
foreach ($pieces as $i => $piece) {
$fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
$toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
$upOptions = array(
// The file to upload.
$ossClient::OSS_FILE_UPLOAD => $uploadFile,
// Set the part number.
$ossClient::OSS_PART_NUM => ($i + 1),
// Specify the start position of the part to upload.
$ossClient::OSS_SEEK_TO => $fromPos,
// Specify the file length.
$ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
// Specifies whether to enable MD5 validation. true: enable. false: disable.
$ossClient::OSS_CHECK_MD5 => $isCheckMd5,
);
// Enable MD5 validation.
if ($isCheckMd5) {
$contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
$upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
}
try {
// Upload the part.
$responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions);
} catch(OssException $e) {
printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} OK\n");
}
// $uploadParts is an array that consists of the ETag and part number of each part.
$uploadParts = array();
foreach ($responseUploadPart as $i => $eTag) {
$uploadParts[] = array(
'PartNumber' => ($i + 1),
'ETag' => $eTag,
);
}
/**
* Step 3: Complete the upload.
*/
try {
// When you call the completeMultipartUpload operation, you must provide all valid $uploadParts. After OSS receives the submitted $uploadParts, it verifies the validity of each part. After all parts are verified, OSS combines them into a complete file.
$ret = $ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts);
// View the version information of the object.
print("versionId:" .$ret[OssClient::OSS_HEADER_VERSION_ID]);
} catch(OssException $e) {
printf(__FUNCTION__ . ": completeMultipartUpload FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": completeMultipartUpload OK\n");
Pour plus d'informations sur les téléchargements en plusieurs parties, consultez les opérations telles que InitiateMultipartUpload, UploadPart et CompleteMultipartUpload.