Baixe um objeto de um bucket para a memória local usando o método de download simples.
Importante
O código de exemplo neste tópico usa a região China (Hangzhou) (cn-hangzhou) e um endpoint público por padrão. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre os mapeamentos entre regiões e endpoints, consulte Regiões e endpoints do OSS.
Permissões
Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não têm permissões iniciais. A conta Alibaba Cloud ou o administrador deve conceder as permissões de operação por meio de políticas do RAM ou Bucket Policy.
|
API |
Ação |
Descrição |
|
GetObject |
|
Baixa um objeto. |
|
|
Necessária ao especificar a versão do objeto via versionId durante o download. |
|
|
|
Necessária se os metadados do objeto contiverem X-Oss-Server-Side-Encryption: KMS durante o download. |
Código de exemplo
O código a seguir baixa um objeto de um bucket para a memória local.
using OSS = AlibabaCloud.OSS.V2; // Create an alias for Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. Specify the region where the bucket is located. Example: cn-hangzhou for China (Hangzhou).
var bucket = "your bucket name"; // Required. Specify the name of the destination bucket.
var endpoint = null as string; // Optional. Specify the domain name used to access OSS. Example: https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
var key = "your object key"; // Required. Specify the name of the object to be downloaded. Format: folder/objectName.
// Load the default configurations of OSS SDK. The configurations automatically read credential information (such as AccessKey) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set the use of environment variables to obtain credentials for identity verification. Format: OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket for the configuration.
cfg.Region = region;
// If an endpoint is specified, overwrite the default endpoint.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance based on the configuration information.
using var client = new OSS.Client(cfg);
// Call the GetObjectAsync method. By default, the object is obtained in streaming mode. In this case, only the response header is downloaded, and the content is returned as a stream.
var result = await client.GetObjectAsync(new OSS.Models.GetObjectRequest()
{
Bucket = bucket,
Key = key,
});
// To read all the content into the memory at a time, you can use this reload method.
//var result = await client.GetObjectAsync(new OSS.Models.GetObjectRequest() {
// Bucket = bucket,
// Key = key,
//},System.Net.Http.HttpCompletionOption.ResponseContentRead);
// Obtain the content stream of the response.
using var body = result.Body;
// Read data.
var reader = new StreamReader(body!);
// Read all content from the stream as a string (the content is loaded into the memory).
var data = reader.ReadToEnd();
// Print the result information.
Console.WriteLine("GetObject done"); // A message indicating that the operation is complete.
Console.WriteLine($"StatusCode: {result.StatusCode}"); // HTTP status code.
Console.WriteLine($"RequestId: {result.RequestId}"); // RequestId, which is used for troubleshooting in Alibaba Cloud.
Console.WriteLine("Response Headers:"); // Response header information.
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value)); // Traverse and print all response headers.
Referências
Para ver o código de exemplo completo sobre como baixar um objeto para a memória local, consulte GetObject.cs.