Você pode chamar a operação AppendObject para anexar conteúdo a objetos anexáveis existentes.
Observações
Neste tópico, o endpoint público da região China (Hangzhou) é usado como exemplo. Para acessar o OSS a partir de outros Alibaba Cloud services na mesma região do OSS, use um endpoint interno. Para obter 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 uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Initialization (C# SDK V1).
Se o objeto ao qual você deseja anexar conteúdo não existir, a operação AppendObject cria um objeto anexável.
-
Se o objeto ao qual você deseja anexar conteúdo já existir:
Se o objeto for anexável e a posição especificada para o início da operação de append for igual ao tamanho atual do objeto, os dados são adicionados ao final do objeto.
Se o objeto for anexável e a posição especificada para o início da operação de append não for igual ao tamanho atual do objeto, o erro PositionNotEqualToLength é retornado.
Se o objeto não for anexável, o erro ObjectNotAppendable é retornado.
Permissões
Por padrão, uma conta Alibaba Cloud tem permissões completas. Usuários RAM ou funções RAM vinculados a uma conta Alibaba Cloud não têm nenhuma permissão por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder permissões de operação por meio de RAM policies ou Bucket Policy.
|
API |
Ação |
Descrição |
|
AppendObject |
|
Permite fazer upload de um objeto anexando-o a um objeto existente. |
|
|
Necessária ao fazer upload de um objeto por append quando tags são especificadas via x-oss-tagging. |
Exemplos
O exemplo a seguir demonstra como fazer upload de um objeto usando append upload:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the path of the local file, the file is uploaded from the path of the project to which the sample program belongs.
var localFilename = "D:\\localpath\\examplefile.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located 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 based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
c.SetRegion(region);
// The position for the first append upload is 0, and the position for the next append upload is included in the response. The position from which the next append operation starts is the current length of the object.
long position = 0;
try
{
var metadata = client.GetObjectMetadata(bucketName, objectName);
position = metadata.ContentLength;
}
catch (Exception) { }
try
{
using (var fs = File.Open(localFilename, FileMode.Open))
{
var request = new AppendObjectRequest(bucketName, objectName)
{
ObjectMetadata = new ObjectMetadata(),
Content = fs,
Position = position
};
// Perform the append operation.
var result = client.AppendObject(request);
// Specify the position from which the append operation starts.
position = result.NextAppendPosition;
Console.WriteLine("Append object succeeded, next append position:{0}", position);
}
// Query the position from which the next append operation starts and perform the second append operation.
using (var fs = File.Open(localFilename, FileMode.Open))
{
var request = new AppendObjectRequest(bucketName, objectName)
{
ObjectMetadata = new ObjectMetadata(),
Content = fs,
Position = position
};
var result = client.AppendObject(request);
position = result.NextAppendPosition;
Console.WriteLine("Append object succeeded, next append position:{0}", position);
}
}
catch (Exception ex)
{
Console.WriteLine("Append object failed, {0}", ex.Message);
}
Referências
Para acessar o código de exemplo completo utilizado para realizar append upload, acesse GitHub.
Para obter mais informações sobre a operação de API utilizada para realizar append upload, consulte AppendObject.