Este tópico descreve como fazer upload de objetos para um bucket com versionamento habilitado.
Precauções
Neste tópico, o endpoint público da região china (Hangzhou) é usado como exemplo. Para acessar o OSS a partir de outros serviços Alibaba Cloud na mesma região, use um endpoint interno. Para mais detalhes sobre regiões e endpoints compatíveis, consulte Regions and endpoints.
Este tópico demonstra como crie uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token service (STS), consulte Create an OssClient.
Para fazer upload de um objeto, você precisa ter a permissão
oss:PutObject. Para mais informações, consulte Grant custom permissions to a RAM user.
Upload simples
Em um bucket com versionamento habilitado, o OSS gera uma string aleatória globalmente única como ID de versão para cada objeto recém-enviado. Esse ID é retornado no campo x-oss-version-id do cabeçalho de resposta.
Em um bucket com versionamento suspenso, o OSS gera um ID de versão "null" para cada objeto recém-enviado. Ao fazer upload de um objeto com o mesmo nome, o novo objeto substituirá o anterior. Isso significa que o objeto terá apenas uma versão, com ID "null".
O código a seguir mostra como realizar um upload simples:
<?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");
Para mais informações sobre uploads simples, consulte PutObject.
Upload por append
Ao adicionar dados a um objeto (AppendObject) em um bucket versionado, observe os seguintes pontos:
A operação AppendObject só pode ser executada em um objeto cuja versão atual seja do tipo Appendable.
Não é possível executar AppendObject em um objeto cuja versão atual não seja do tipo Appendable, como um Normal Object ou um Delete Marker. Essa operação também não é permitida quando apenas as versões históricas do objeto são do tipo Appendable.
Ao executar AppendObject em um objeto cuja versão atual é do tipo Appendable, o OSS não cria uma versão histórica para esse objeto.
Ao executar PutObject ou DeleteObject em um objeto cuja versão atual é do tipo Appendable, o OSS salva o objeto Appendable como versão histórica. A partir desse momento, não é mais possível adicionar dados a esse objeto.
O código a seguir mostra como realizar um upload por append:
<?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");
Para mais informações sobre uploads por append, consulte AppendObject.
Upload multipart
Em um bucket versionado, chame a operação CompleteMultipartUpload para concluir um upload multipart. O OSS gera um ID de versão único para o objeto completo e o retorna no campo x-oss-version-id do cabeçalho de resposta.
O código a seguir mostra como realizar um upload multipart:
<?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");
Para mais informações sobre uploads multipart, consulte operações como InitiateMultipartUpload, UploadPart e CompleteMultipartUpload.