Todos os produtos
Search
Central de documentação

Object Storage Service:Resumable upload (OSS SDK for C# 1.0)

Última atualização: Jul 03, 2026

Ao fazer upload de um objeto para o Object Storage Service (OSS) com upload retomável, especifique um diretório para o arquivo de checkpoint que armazena o progresso da transferência. Se ocorrer falha no upload devido a exceções de rede ou erros de programa, a tarefa será retomada a partir da posição registrada nesse arquivo de checkpoint.

O sistema registra o progresso do upload atual no arquivo de checkpoint durante o processo. Caso alguma parte falhe, o próximo upload começa da posição salva no arquivo de checkpoint. Esse arquivo é excluído automaticamente após a conclusão bem-sucedida da tarefa de upload retomável.

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, utilize um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • A documentação 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 Inicialização (C# SDK V1).

  • Para utilizar o upload retomável, você precisa da permissão oss:PutObject. Para mais detalhes, consulte Conceder uma política personalizada.

Código de exemplo

O código abaixo ilustra como executar um upload retomável:

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 that you want to upload. Example: D:\\localpath\\examplefile.txt. 
// By default, if you specify only the name of the local file such as examplefile.txt without specifying the local path, the local file is uploaded from the path of the project to which the sample program belongs. 
var localFilename = "D:\\localpath\\examplefile.txt";
// Specify the checkpoint file. The checkpoint file stores information about the upload progress. 
string checkpointDir = "yourCheckpointDir";
// 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);
client.SetRegion(region);
try
{
    // Configure parameters by using UploadFileRequest. 
    UploadObjectRequest request = new UploadObjectRequest(bucketName, objectName, localFilename)
    {
        // Specify the size of each part. 
        PartSize = 8 * 1024 * 1024,
        // Specify the number of concurrent threads. 
        ParallelThreadCount = 3,
        // Specify the checkpointDir parameter to store the state of the resumable upload task, which is used to resume the upload task if the upload task fails. 
        // If you set checkpointDir to null, resumable upload does not take effect and the object is re-uploaded if the object fails to be uploaded. 
        CheckpointDir = checkpointDir,
    };
    // Start resumable upload. 
    client.ResumableUploadObject(request);
    Console.WriteLine("Resumable upload object:{0} succeeded", objectName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}

Referências

Para acessar o código de exemplo completo de upload retomável, visite o GitHub.