Los objetos almacenados en Object Storage Service (OSS) se componen de claves, datos y metadatos. Los metadatos describen el objeto e incluyen encabezados HTTP estándar y metadatos de usuario. Al configurar los encabezados HTTP estándar, puede crear políticas personalizadas para las solicitudes HTTP, como políticas de caché o de descarga forzada de objetos. Además, configure los metadatos de usuario de un objeto para identificar sus propósitos o atributos.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, 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 instance.
Para configurar los metadatos de un objeto, requiere el permiso
oss:PutObject. Para consultarlos, necesita el permisooss:GetObject. Para obtener más información, consulte Grant a custom policy.
Establecer metadatos de objetos
A continuación se muestra cómo establecer los metadatos de un objeto mediante código.
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Set HTTP headers. */
auto meta = ObjectMetaData();
meta.setContentType("text/plain");
meta.setCacheControl("max-age=3");
/* Set custom object metadata. */
meta.UserMetaData()["meta"] = "meta-value";
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "Thank you for using Alibaba Cloud Object Storage Service!";
auto outcome = client.PutObject(BucketName, ObjectName, content, meta);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
Obtener metadatos de objetos
Puede recuperar los metadatos de un objeto con cualquiera de los siguientes métodos:
|
Método |
Descripción |
Ventaja |
|
GetObjectMeta |
Obtiene el ETag, el tamaño y la fecha de última modificación de un objeto. |
Más ligero y rápido |
|
HeadObject |
Recupera todos los metadatos de un objeto. |
Ninguna |
El siguiente ejemplo de código muestra cómo consultar los metadatos de un objeto:
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Get partial metadata of the object. */
auto outcome = client.GetObjectMeta(BucketName, ObjectName);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "GetObjectMeta fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
else {
auto metadata = outcome.result();
std::cout << " get metadata success, ETag:" << metadata.ETag() << "; LastModified:"
<< metadata.LastModified() << "; Size:" << metadata.ContentLength() << std::endl;
}
/* Get all metadata of the object. */
outcome = client.HeadObject(BucketName, ObjectName);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "HeadObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
else {
auto headMeta = outcome.result();
std::cout <<"headMeta success, ContentType:"
<< headMeta.ContentType() << "; ContentLength:" << headMeta.ContentLength()
<< "; CacheControl:" << headMeta.CacheControl() << std::endl;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
Referencias
Para consultar el código de ejemplo completo que muestra cómo establecer y recuperar metadatos de objetos, visite GitHub.
Para obtener más información sobre la operación de API que permite configurar metadatos de objetos durante una carga simple, consulte PutObject.
Si desea conocer más detalles acerca de las operaciones de API para consultar metadatos de objetos, consulte GetObjectMeta y HeadObject.