Todos os produtos
Search
Central de documentação

Object Storage Service:Upload files (C# SDK V1)

Última atualização: Sep 22, 2026

Este tópico descreve como fazer upload de arquivos (objetos) para um bucket com versionamento habilitado.

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 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 como criar 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).

  • Para fazer upload de um objeto, você precisa ter a permissão oss:PutObject. Para mais informações, consulte Grant a custom policy.

Upload simples

Ao enviar uma solicitação de upload de objeto para um bucket com versionamento habilitado, o OSS gera um ID de versão exclusivo para o objeto enviado e inclui esse ID na resposta como valor do cabeçalho x-oss-version-id. Ao fazer upload de um objeto para um bucket com versionamento suspenso, o OSS gera um ID de versão null para o objeto. Se o objeto enviado tiver o mesmo nome de um objeto existente, o objeto existente será sobrescrito pelo novo. Dessa forma, cada objeto terá apenas uma versão cujo ID é null.

O código a seguir mostra como executar 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 append

Em um bucket com versionamento habilitado, a operação AppendObject só pode ser executada na versão atual de um objeto do tipo appendable.

Nota
  • Ao executar a operação AppendObject na versão atual de um objeto appendable, o OSS não gera uma versão anterior para esse objeto.

  • Ao executar a operação PutObject ou DeleteObject em um objeto cuja versão atual é appendable, o OSS armazena o objeto appendable como versão anterior e impede que novos dados sejam acrescentados a ele.

  • Não é possível executar a operação AppendObject em um objeto cuja versão atual não seja appendable, como um objeto normal ou um delete marker.

O código a seguir mostra como executar um upload por append:

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 multipart

Ao chamar a operação CompleteMultipartUpload para concluir a tarefa de upload multipart de um objeto em um bucket com versionamento habilitado, o OSS gera um ID de versão exclusivo para o objeto e retorna esse ID como valor do cabeçalho x-oss-version-id na resposta.

O código a seguir mostra como executar um upload multipart:

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