Os objetos armazenados no Object Storage Service (OSS) são compostos por chaves, dados e metadados. Os metadados descrevem os atributos do objeto e incluem cabeçalhos HTTP padrão e metadados definidos pelo usuário. Configure cabeçalhos HTTP padrão para criar políticas de requisição HTTP personalizadas, como políticas de cache e políticas de download forçado. Adicione metadados de usuário ao objeto para identificar suas finalidades ou atributos.
Observações sobre o uso
Neste tópico, o endpoint público da região China (Hangzhou) é utilizado. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre regiões e endpoints compatíveis, consulte Regions and endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para mais informações, consulte 配置访问凭证.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como o uso de um domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Client configuration.
Para configurar metadados de objetos, você deve ter a permissão
oss:PutObject. Para consultar metadados de objetos, você deve ter a permissãooss:GetObject. Para mais informações, consulte Grant a custom policy.
Configure metadados de objetos
Os exemplos a seguir demonstram como configurar cabeçalhos HTTP padrão e metadados de usuário.
-
Configure cabeçalhos HTTP padrão
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.common.utils.BinaryUtil; import com.aliyun.oss.common.utils.DateUtil; import com.aliyun.oss.model.ObjectMetadata; import java.io.ByteArrayInputStream; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt. String objectName = "testfolder/exampleobject.txt"; String content = "Hello OSS"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Add metadata for the uploaded object. ObjectMetadata meta = new ObjectMetadata(); String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(content.getBytes())); // Enable MD5 verification. After MD5 verification is enabled, OSS calculates the MD5 hash of the uploaded object and compares this MD5 hash with that specified in the request. If the two values are different, an error is reported. meta.setContentMD5(md5); // Specify the type of content to upload. The browser determines the format and encoding type that are used to read the object based on the content type of the object. If the content type is not specified, a content type is generated based on the object name extension. If no extension is available, the default value application/octet-stream is used as the content type. meta.setContentType("text/plain; charset=utf-8"); // Configure the headers. For example, specify the storage class for uploaded files. meta.setHeader("x-oss-storage-class", StorageClass.Standard); // To enable the following configurations as needed, uncomment the corresponding lines. // Specify a name for the object when the content is downloaded. // meta.setContentDisposition("attachment; filename=\"DownloadFilename\""); // Specify the length of the object to upload. If the actual object length is greater than the specified length, the object is truncated. Only the content of the specified length is uploaded. If the actual object length is smaller than the specified length, all content of the object is uploaded. // meta.setContentLength(content.length()); // Specify the caching behavior of the web page when the content is downloaded. // meta.setCacheControl("Download Action"); // Specify the expiration time of the cache in UTC. // meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z")); // Specify the content encoding format when the content is downloaded. // meta.setContentEncoding("gzip"); // Upload the object. ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), meta); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }Para mais informações sobre cabeçalhos HTTP, consulte RFC 2616.
-
Configure metadados de usuário para descrever um objeto
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.ObjectMetadata; import java.io.ByteArrayInputStream; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt. String objectName = "testfolder/exampleobject.txt"; String content = "Hello OSS"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Add metadata for the object. ObjectMetadata meta = new ObjectMetadata(); // Specify custom metadata. We recommend that you use the Base64 encoding method. meta.addUserMetadata("key1", "value1"); meta.addUserMetadata("key2", "value2"); // Upload the object. ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), meta); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }Os metadados de um objeto são baixados junto com o objeto. Um objeto pode ter múltiplos registros de metadados, com tamanho total não superior a 8 KB.
Modifique metadados de objetos
O exemplo a seguir demonstra como modificar os metadados de um objeto:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the source bucket.
String sourceBucketName = "yourSourceBucketName";
// Specify the full path of the source object.
String sourceObjectName = "yourSourceObjectName";
// Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket.
String destinationBucketName = "yourDestinationBucketName";
// Specify the full path of the destination object.
String destinationObjectName = "yourDestinationObjectName";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Specify that the source object is the same as the destination object. Call the ossClient.copyObject method to modify the object metadata.
CopyObjectRequest request = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
ObjectMetadata meta = new ObjectMetadata();
// Specify the type of content to upload. The browser determines the format and encoding type that are used to read the object based on the content type of the object. If the content type is not specified, a content type is generated based on the object name extension. If no extension is available, the default value application/octet-stream is used as the content type.
meta.setContentType("text/plain; charset=utf-8");
// Configure the headers. For example, specify the storage class for uploaded files.
meta.setHeader("x-oss-storage-class", StorageClass.Standard);
// To enable the following configurations as needed, uncomment the corresponding lines.
// Specify a name for the object when the content is downloaded.
// meta.setContentDisposition("attachment; filename=\"DownloadFilename\"");
// Specify the length of the object that can be uploaded. If the actual object length is greater than the specified length, only the specified length of the content is uploaded and the trailing part is truncated. If the actual object length is smaller than the specified length, all content of the object is uploaded.
// meta.setContentLength(content.length());
// Specify the caching behavior of the web page when the content is downloaded.
// meta.setCacheControl("Download Action");
// Specify the expiration time of the cache in UTC.
// meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
// Specify the content encoding format when the content is downloaded.
// meta.setContentEncoding("gzip");
// Specify custom metadata. We recommend that you use the Base64 encoding method.
meta.addUserMetadata("key1", "value1");
meta.addUserMetadata("key2", "value2");
request.setNewObjectMetadata(meta);
// Modify the object metadata.
ossClient.copyObject(request);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Consulte metadados de objetos
A tabela a seguir lista os métodos disponíveis para consultar metadados de objetos.
|
Método |
Descrição |
|
ossClient.getSimplifiedObjectMeta |
Consulta os valores de ETag, Size e LastModified do objeto por meio da operação GetObjectMeta. |
|
ossClient.getObjectMetadata |
Recupera todos os metadados do objeto por meio da operação HeadObject. |
O exemplo a seguir demonstra como consultar metadados de objetos:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.SimplifiedObjectMeta;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt.
String objectName = "testfolder/exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Specify the bucket name and the full path of the object in the bucket.
// Query partial metadata of the object.
SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(bucketName, objectName);
System.out.println("Query partial metadata of the object");
System.out.println(objectMeta.getSize());
System.out.println(objectMeta.getETag());
System.out.println(objectMeta.getLastModified());
// Query object metadata, including the last access time of the object (X-Oss-Last-Access-Time), after the access tracking feature is enabled. You can only use OSS SDK for Java V3.16.0 or later to query X-Oss-Last-Access-Time.
System.out.println(objectMeta.getHeaders().get("x-oss-last-access-time"));
// Query all metadata of the object.
ObjectMetadata metadata = ossClient.getObjectMetadata(bucketName, objectName);
System.out.println("Query partial metadata of the object");
System.out.println(metadata.getContentType());
System.out.println(metadata.getLastModified());
System.out.println(metadata.getExpirationTime());
System.out.println(metadata.getETag());
System.out.println(metadata.getContentMD5());
System.out.println(metadata.getContentLength());
System.out.println(metadata.getObjectType());
System.out.println(metadata.getUserMetadata());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Referências
Para mais informações sobre metadados de objetos, consulte Manage object metadata.
Para acessar o código de exemplo completo utilizado para configurar e consultar metadados de objetos, visite GitHub.
Para mais informações sobre a operação de API utilizada para configurar metadados de objetos durante o upload simples, consulte PutObject.
Para mais informações sobre as operações de API disponíveis para consultar metadados de objetos, consulte GetObjectMeta e HeadObject.