Todos os produtos
Search
Central de documentação

Object Storage Service:Multipart upload (C# SDK V2)

Última atualização: Sep 09, 2026

O Object Storage Service (OSS) oferece o recurso de upload multipartido. Esse recurso permite dividir um objeto grande em várias partes e enviá-las separadamente. Após enviar todas as partes, chame a operação CompleteMultipartUploadAsync para combiná-las em um objeto completo.

Observações

  • O código de exemplo neste tópico usa o ID da região cn-hangzhou, referente à região China (Hangzhou), e utiliza o endpoint público por padrão. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use o endpoint interno. Para mais informações sobre as regiões e endpoints compatíveis com o OSS, consulte Regions and endpoints.

  • Para fazer um upload multipartido, você precisa da permissão oss:PutObject. Para mais detalhes, consulte Grant custom permissions to a RAM user.

Processo de upload multipartido

O upload multipartido consiste em três etapas:

  1. Inicialize uma tarefa de upload multipartido.

    Chame o método Client.InitiateMultipartUploadAsync para obter um ID de upload globalmente exclusivo do OSS.

  2. Envie as partes.

    Use o método Client.UploadPartAsync para enviar os dados de cada parte.

    Nota
    • Para um mesmo ID de upload, o número da parte identifica sua posição relativa dentro do objeto completo. Se você enviar novos dados usando o mesmo número de parte, os dados existentes dessa parte no OSS serão sobrescritos.

    • O OSS inclui o hash MD5 dos dados da parte enviada no cabeçalho ETag da resposta.

    • O OSS calcula o hash MD5 dos dados enviados e o compara com o hash MD5 calculado pelo kit de desenvolvimento de software (SDK). Caso os dois hashes não coincidam, o OSS retorna o código de erro InvalidDigest.

  3. Conclua a tarefa de upload multipartido.

    Após enviar todas as partes, chame o método Client.CompleteMultipartUploadAsync para combiná-las em um objeto completo.

Código de exemplo

O código a seguir demonstra como dividir um arquivo local grande em várias partes, enviá-las simultaneamente para um bucket e, em seguida, combiná-las em um objeto completo.

using OSS = AlibabaCloud.OSS.V2;  // Create an alias for the Alibaba Cloud OSS SDK to simplify its use.

var region = "cn-hangzhou";  // Required. The region where the bucket is located. This example uses China (Hangzhou). Set Region to cn-hangzhou.
var endpoint = null as string;  // Optional. The domain name to access OSS. This example uses China (Hangzhou). Set Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var bucket = "you bucket name";  // Required. The bucket name.
var key = "your object key";  // Required. The name of the object to upload.
var partSize = 512*1024;  // Required. The size of each part. This example uses 512 * 1024, which is 512 KB.
var filePath = "filePath";  // Required. The path of the file to upload.

// Load the default configurations of the OSS SDK. These configurations automatically read credentials, such as the AccessKey, from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly configure the client to obtain credentials from environment variables for identity verification. The format is OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the bucket region 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.
using var client = new OSS.Client(cfg); 

// Initialize the multipart upload.
var initResult = await client.InitiateMultipartUploadAsync(new()
{
    Bucket = bucket,
    Key = key
});

// Open the file to upload.
using var file = File.OpenRead(filePath);
long fileSize = file.Length;
long partNumber = 1;

// Store the information of all uploaded parts.
var uploadParts = new List<OSS.Models.UploadPart>();

// Upload the file in parts.
for (long offset = 0; offset < fileSize; offset += partSize)
{
    // Calculate the size of the current part.
    var size = Math.Min(partSize, fileSize - offset);
    // Upload a single part.
    var upResult = await client.UploadPartAsync(new()
    {
        Bucket = bucket,
        Key = key,
        PartNumber = partNumber,
        UploadId = initResult.UploadId,
        Body = new OSS.IO.BoundedStream(file, offset, size)
    });

    // Save the part information to complete the upload later.
    uploadParts.Add(new() { PartNumber = partNumber, ETag = upResult.ETag });
    partNumber++;
}

// Sort the parts by part number.
uploadParts.Sort((left, right) => { return (left.PartNumber > right.PartNumber) ? 1 : -1; });

// Complete the multipart upload.
var cmResult = await client.CompleteMultipartUploadAsync(new()
{
    Bucket = bucket,
    Key = key,
    UploadId = initResult.UploadId,
    CompleteMultipartUpload = new ()
    {
        Parts = uploadParts
    }
});

// Print the upload result.
Console.WriteLine("MultipartUpload done");  // Indicate that the operation is complete.
Console.WriteLine($"StatusCode: {cmResult.StatusCode}");  // The HTTP status code.
Console.WriteLine($"RequestId: {cmResult.RequestId}");  // The request ID, which is used for troubleshooting in Alibaba Cloud.
Console.WriteLine("Response Headers:");  // The response headers.
cmResult.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value));  // Traverse and print all response headers.

Documentos relacionados

Para acessar o código de exemplo completo de upload multipartido, consulte multipartUpload.cs.