Este tópico descreve como fazer upload de arquivos (objetos) para um bucket com versionamento ativado.
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, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e 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 Inicialização (C# SDK V1).
Para fazer upload de um objeto, você precisa da permissão
oss:PutObject. Para mais detalhes, consulte Conceder uma política personalizada.
Upload simples
Ao iniciar uma solicitação de upload de objeto para um bucket com versionamento ativado, o OSS gera um ID de versão exclusivo para o objeto enviado e o inclui na resposta como valor do cabeçalho x-oss-version-id. Se você fizer o upload em um bucket com versionamento suspenso, o OSS atribui ao objeto um ID de versão nulo. Caso já exista um objeto com o mesmo nome, o novo arquivo substituirá o existente. Dessa forma, cada objeto terá apenas uma versão com ID nulo.
O código a seguir mostra como fazer um upload simples:
using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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 = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this 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");
// Set bucketName to the name of the bucket, for example, examplebucket.
var bucketName = "examplebucket";
// Set objectName to the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt.
var objectName = "exampleobject.txt";
var objectContent = "More than just cloud.";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
MemoryStream requestContent = new MemoryStream(binaryData);
// Upload the object.
var result = client.PutObject(bucketName, objectName, requestContent);
Console.WriteLine("Put object succeeded versionid : {0}", result.VersionId);
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}
Upload por acréscimo
Em buckets com versionamento ativado, a operação AppendObject só pode ser executada na versão atual de um objeto anexável.
Ao executar a operação AppendObject na versão atual de um objeto anexável, o OSS não gera uma versão anterior para esse objeto.
Se você executar a operação PutObject ou DeleteObject em um objeto cuja versão atual seja anexável, o OSS armazenará o objeto anexável como uma versão anterior e impedirá novos acréscimos.
Não é possível executar a operação AppendObject em objetos cuja versão atual não seja anexável, como objetos normais ou marcadores de exclusão.
O código a seguir mostra como fazer um upload por acréscimo:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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 = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this 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");
// Set bucketName to the name of the bucket, for example, examplebucket.
var bucketName = "examplebucket";
// Set objectName to the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt.
var objectName = "exampleobject.txt";
// Set localFilename to the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the project directory of the sample program.
var localFilename = "D:\\localpath\\examplefile.txt";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// The position for the first append operation is 0. The response contains the position for the next append operation. The position for subsequent append operations is the length of the object before the append.
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
};
// Append data to the object.
var result = client.AppendObject(request);
// Set the position for the append operation.
position = result.NextAppendPosition;
Console.WriteLine("Append object succeeded, next append position:{0}, vesionid:{1}", position, result.VersionId);
}
// Get the append position and append data to the object again.
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}, vesionid:{1}", position, result.VersionId);
}
}
catch (Exception ex)
{
Console.WriteLine("Append object failed, {0}", ex.Message);
}
Upload multipartido
Ao chamar a operação CompleteMultipartUpload para concluir uma tarefa de upload multipartido em um bucket com versionamento ativado, o OSS gera um ID de versão exclusivo para o objeto e o retorna como valor do cabeçalho x-oss-version-id na resposta.
O código a seguir mostra como fazer um upload multipartido:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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 = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this 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");
// Set bucketName to the name of the bucket, for example, examplebucket.
var bucketName = "examplebucket";
// Set objectName to the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Set localFilename to the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the project directory of the sample program.
var localFilename = "D:\\localpath\\examplefile.txt";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// Initialize the multipart upload.
var uploadId = "";
try
{
// Specify the name of the object to upload and the bucket where it is stored. In InitiateMultipartUploadRequest, you can set ObjectMeta, but you do not need to specify ContentLength.
var request = new InitiateMultipartUploadRequest(bucketName, objectName);
var result = client.InitiateMultipartUpload(request);
uploadId = result.UploadId;
// Print the UploadId.
Console.WriteLine("Init multi part upload succeeded");
Console.WriteLine("Upload Id:{0}", result.UploadId);
}
catch (Exception ex)
{
Console.WriteLine("Init multi part upload failed, {0}", ex.Message);
}
// Calculate the total number of parts.
var partSize = 100 * 1024;
var fi = new FileInfo(localFilename);
var fileSize = fi.Length;
var partCount = fileSize / partSize;
if (fileSize % partSize != 0)
{
partCount++;
}
// Start the multipart upload. partETags is a list that stores the ETag of each part. After OSS receives the part list, it verifies each part. After all parts are verified, OSS combines them into a complete object.
var partETags = new List<PartETag>();
try
{
using (var fs = File.Open(localFilename, FileMode.Open))
{
for (var i = 0; i < partCount; i++)
{
var skipBytes = (long)partSize * i;
// Go to the start position for the current upload.
fs.Seek(skipBytes, 0);
// Calculate the size of the part to upload. The size of the last part is the remaining data size.
var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
var request = new UploadPartRequest(bucketName, objectName, uploadId)
{
InputStream = fs,
PartSize = size,
PartNumber = i + 1
};
// Call the UploadPart operation to upload the part. The response contains the ETag of the part.
var result = client.UploadPart(request);
partETags.Add(result.PartETag);
Console.WriteLine("finish {0}/{1}", partETags.Count, partCount);
}
Console.WriteLine("Put multi part upload succeeded");
}
}
catch (Exception ex)
{
Console.WriteLine("Put multi part upload failed, {0}", ex.Message);
}
// Complete the multipart upload.
try
{
var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId);
foreach (var partETag in partETags)
{
completeMultipartUploadRequest.PartETags.Add(partETag);
}
var result = client.CompleteMultipartUpload(completeMultipartUploadRequest);
Console.WriteLine("CompleteMultipartUpload succeeded, vesionid:{0}", result.VersionId);
}
catch (Exception ex)
{
Console.WriteLine("complete multi part failed, {0}", ex.Message);
}
Referências
Para mais informações sobre upload simples, consulte PutObject.
Para detalhes sobre upload por acréscimo, consulte AppendObject.
Para saber mais sobre upload multipartido, consulte CompleteMultipartUpload.