O upload por acréscimo permite adicionar conteúdo diretamente ao final de um objeto anexável existente usando o OSS C# SDK.
Precauções
O código de exemplo utiliza a região China (Hangzhou) (
cn-hangzhou) e o endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use o endpoint interno. Para obter mais informações sobre regiões e endpoints suportados, consulte Regiões e endpoints do OSS.Se o objeto não existir, um objeto anexável será criado.
-
Se o objeto já existir:
Quando o objeto for anexável e a posição de acréscimo especificada corresponder ao tamanho atual do objeto, o conteúdo será adicionado ao final dele.
Caso o objeto seja anexável, mas a posição de acréscimo especificada não corresponder ao tamanho atual, a exceção PositionNotEqualToLength será lançada.
Se o objeto não for do tipo anexável, como um objeto normal criado por upload simples, a exceção ObjectNotAppendable será lançada.
Permissões
Por padrão, uma conta Alibaba Cloud possui permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não têm nenhuma permissão por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de políticas do RAM ou Bucket Policy.
|
API |
Ação |
Descrição |
|
AppendObject |
|
Use esta operação para fazer upload de um objeto acrescentando-o a um objeto existente. |
|
|
Necessária quando tags de objeto são especificadas via x-oss-tagging durante o upload por acréscimo. |
Código de exemplo
using System.Text; // Import the System.Text namespace to process character encoding, such as UTF-8 encoded strings.
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. This topic uses China (Hangzhou) as an example. Set the region to cn-hangzhou.
var bucket = "your bucket name"; // Required. Specify the name of the destination bucket.
var endpoint = null as string; // Optional. Specify the endpoint that is used to access OSS. This topic uses China (Hangzhou) as an example. Set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var key = "your object key"; // Required. Specify the name of the object to which you want to append data. Format: folder/objectName.
// Load the default configurations of OSS SDK. The configurations automatically read credential information, such as AccessKeys, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly specify that environment variables are used 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 in the configuration.
cfg.Region = region;
// If an endpoint is specified, it overwrites the default endpoint.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance using the configuration information.
using var client = new OSS.Client(cfg);
// Define the first part of the content to be appended to the OSS object.
var content1 = "hello,";
// Define the second part of the content to be appended to the OSS object.
var content2 = "oss!";
// Call the AppendObjectAsync method to perform the first append operation.
var result1 = await client.AppendObjectAsync(new OSS.Models.AppendObjectRequest()
{
// Specify the destination bucket.
Bucket = bucket,
// Specify the name of the destination object.
Key = key,
// For the first append operation, the start position must be 0.
Position = 0,
Body = new MemoryStream(Encoding.UTF8.GetBytes(content1))
});
// Call the AppendObjectAsync method to perform the second append operation, starting from the end position of the previous operation.
var result2 = await client.AppendObjectAsync(new OSS.Models.AppendObjectRequest()
{
// The destination bucket remains unchanged.
Bucket = bucket,
// The name of the destination object remains unchanged.
Key = key,
// Continue writing from the end position of the previous append operation.
Position = result1.NextAppendPosition,
Body = new MemoryStream(Encoding.UTF8.GetBytes(content2))
});
// Print the upload result.
Console.WriteLine("AppendObject done"); // A message indicates that the operation is complete.
Console.WriteLine($"StatusCode: {result2.StatusCode}"); // The HTTP status code.
Console.WriteLine($"RequestId: {result2.RequestId}"); // The request ID, which is used for troubleshooting in Alibaba Cloud.
Console.WriteLine("Response Headers:"); // The response header information.
result2.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value)); // Traverse and print all response headers.
Console.WriteLine($"NextAppendPosition: {result2.NextAppendPosition}"); // Output the start position for the next append operation.
Referências
Para acessar o código de exemplo completo sobre upload por acréscimo, consulte AppendObject.cs.