Por padrão, a operação GetObject retorna apenas a versão atual de um objeto em um bucket com versionamento habilitado.
Informações gerais
Ao chamar a operação GetObject em um bucket, um dos seguintes casos se aplica:
Se a versão atual do objeto for um marcador de exclusão, o OSS retorna 404 Not Found.
Se você especificar o versionId do objeto no parâmetro de consulta, o OSS retorna a versão indicada. Se o versionId for definido como "null", o OSS retorna a versão do objeto com versionId nulo.
Se você tentar recuperar um marcador de exclusão especificando seu versionId, o OSS retorna 405 Method Not Allowed.
Observações
Neste tópico, utiliza-se 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, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.
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 Initialization (C# SDK V1).
Permissões
Por padrão, uma conta da Alibaba Cloud possui permissões completas. Usuários RAM ou funções RAM vinculados a uma conta da Alibaba Cloud não possuem nenhuma permissão por padrão. A conta da Alibaba Cloud ou o administrador da conta deve conceder permissões de operação por meio de RAM policies ou Bucket Policy.
|
API |
Action |
Descrição |
|
GetObject |
|
Baixa um objeto. |
|
|
Ao baixar um objeto, se você especificar a versão por meio do versionId, esta permissão será necessária. |
|
|
|
Ao baixar um objeto, se os metadados do objeto contiverem X-Oss-Server-Side-Encryption: KMS, esta permissão será necessária. |
Código de exemplo
O código de exemplo a seguir demonstra 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.