De forma predeterminada, la operación GetObject devuelve únicamente la versión actual de un objeto almacenado en un bucket con control de versiones habilitado.
Contexto
Cuando se invoca la operación GetObject en un bucket, aplica uno de los siguientes casos:
Si la versión actual del objeto es una marca de eliminación, OSS devuelve 404 Not Found.
Si especifica el versionId del objeto en el parámetro de consulta, se devuelve la versión indicada. Si establece el versionId como "null", se devuelve la versión del objeto cuyo versionId es nulo.
Si intenta recuperar una marca de eliminación al especificar su versionId, OSS devuelve 405 Method Not Allowed.
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 que OSS, 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 Initialization (C# SDK V1).
Permisos
De forma predeterminada, una cuenta de Alibaba Cloud tiene todos los permisos. Los usuarios o roles de RAM asociados a una cuenta de Alibaba Cloud no tienen ningún permiso de manera predeterminada. La cuenta de Alibaba Cloud o su administrador deben otorgar los permisos de operación mediante RAM policies o Bucket Policy.
|
API |
Action |
Descripción |
|
GetObject |
|
Descarga un objeto. |
|
|
Este permiso es obligatorio cuando se descarga un objeto y se especifica su versión mediante versionId. |
|
|
|
Este permiso es obligatorio cuando se descarga un objeto cuyos metadatos incluyen X-Oss-Server-Side-Encryption: KMS. |
Código de ejemplo
A continuación se muestra un ejemplo de código para descargar un 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);
}
}
}
}
Referencias
Para obtener más información sobre la operación de API utilizada para descargar archivos, consulte GetObject.