Este tema describe cómo cargar objetos en un bucket que tiene habilitado el control de versiones.
Precauciones
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si accede a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles, consulte Regions and endpoints.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Create an OssClient.
Para cargar un objeto, debe contar con el permiso
oss:PutObject. Para obtener más información, consulte Grant custom permissions to a RAM user.
Carga simple
Cuando un bucket tiene habilitado el control de versiones, OSS genera una cadena aleatoria única a nivel global como identificador de versión para cada objeto nuevo que se carga. Este identificador se devuelve en el campo x-oss-version-id del encabezado de respuesta.
Si el control de versiones del bucket está suspendido, OSS asigna el identificador de versión "null" a cada objeto nuevo. Al cargar un objeto con el mismo nombre, el nuevo sobrescribe al anterior. Por lo tanto, el objeto conserva una sola versión y su identificador es "null".
A continuación se muestra el código para efectuar una carga 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");
Para obtener más información sobre las cargas simples, consulte PutObject.
Carga por anexión
Al anexar datos a un objeto (AppendObject) dentro de un bucket con control de versiones, tenga en cuenta lo siguiente:
La operación AppendObject solo se aplica a objetos cuya versión actual sea de tipo Appendable.
No es posible ejecutar AppendObject si la versión actual del objeto no es de tipo Appendable, como ocurre con un Normal Object o un Delete Marker. Tampoco funciona cuando únicamente las versiones históricas del objeto son de tipo Appendable.
Si ejecuta AppendObject sobre un objeto cuya versión actual es de tipo Appendable, OSS no crea una versión histórica para dicho objeto.
Cuando ejecuta PutObject o DeleteObject sobre un objeto cuya versión actual es de tipo Appendable, OSS guarda ese objeto como una versión histórica. A partir de ese momento, ya no puede anexarle datos.
El siguiente código muestra cómo llevar a cabo una carga por anexión:
<?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 obtener más información sobre las cargas por anexión, consulte AppendObject.
Carga multiparte
En un bucket con control de versiones, llame a la operación CompleteMultipartUpload para finalizar una carga multiparte. OSS genera un identificador de versión único para todo el objeto y lo devuelve en el campo x-oss-version-id del encabezado de respuesta.
A continuación se presenta el código para ejecutar una carga multiparte:
<?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 obtener más información sobre las cargas multiparte, consulte operaciones como InitiateMultipartUpload, UploadPart y CompleteMultipartUpload.