Por padrão, a operação GetObject retorna apenas a versão atual de um objeto em um bucket com versionamento ativado.
Informações básicas
Ao chamar a operação GetObject em um bucket, uma das seguintes situações se aplica:
Se a versão atual do objeto for um marcador de exclusão, o OSS retorna 404 Not Found.
Caso você especifique o versionId de um objeto no parâmetro de consulta, a versão especificada será retornada. Se definir o versionId como "null", o sistema retorna a versão do objeto que possui um versionId nulo.
Ao tentar recuperar um marcador de exclusão especificando seu versionId, o OSS retorna 405 Method Not Allowed.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
O exemplo aqui demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via credenciais do Security Token Service (STS), veja Inicialização (C# SDK V1).
Permissões
Uma conta Alibaba Cloud possui, por padrão, permissões completas. Usuários RAM ou funções RAM vinculados a essa conta não têm nenhuma permissão inicialmente. A conta Alibaba Cloud ou o administrador deve conceder as permissões operacionais necessárias por meio de políticas do RAM ou Bucket Policy.
|
API |
Ação |
Descrição |
|
GetObject |
|
Baixa um objeto. |
|
|
Necessária quando se especifica a versão do objeto via versionId durante o download. |
|
|
|
Exigida se os metadados do objeto contiverem X-Oss-Server-Side-Encryption: KMS no momento do download. |
Código de exemplo
O código abaixo exemplifica como baixar um objeto:
using System;
using System.IO;
using Aliyun.OSS;
using Aliyun.OSS.Common;
namespace Samples
{
public class Program
{
public static void Main(string[] args)
{
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt.
var downloadFilename = "D:\\localpath\\examplefile.txt";
var versionid = "yourArchiveObjectVersionid";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Download the file to a stream. OssObject contains various information about the file, such as the bucket where the file is stored, the file name, metadata, and an input stream.
var request = new GetObjectRequest(bucketName, objectName)
{
// Specify the version ID of the object.
VersionId = versionid
};
var obj = client.GetObject(request);
using (var requestStream = obj.Content)
{
byte[] buf = new byte[1024];
var fs = File.Open(downloadFilename, FileMode.OpenOrCreate);
var len = 0;
// Read the content of the file to a file or memory using the input stream.
while ((len = requestStream.Read(buf, 0, 1024)) != 0)
{
fs.Write(buf, 0, len);
}
fs.Close();
}
Console.WriteLine("Get object succeeded, vesionid:{0}", versionid);
}
catch (Exception ex)
{
Console.WriteLine("Get object failed. {0}", ex.Message);
}
}
}
}
Referências
Para mais informações sobre a operação de API usada para baixar arquivos, consulte GetObject.