Todos os produtos
Search
Central de documentação

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

Última atualização: Sep 02, 2026

Ao carregar um objeto no 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 devido a exceções de rede ou erros no programa, a tarefa continuará automaticamente a partir da posição registrada nesse arquivo.

O sistema registra o progresso do carregamento atual no arquivo de checkpoint durante o processo. Se alguma parte falhar, o próximo envio recomeçará exatamente da posição salva. Após a conclusão bem-sucedida do upload retomável, o arquivo de checkpoint será excluído.

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 Regions and endpoints.

  • Os exemplos abaixo demonstram como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Initialization (C# SDK V1).

  • Para usar uploads retomáveis, você precisa da permissão oss:PutObject. Para obter mais informações, consulte Grant a custom policy.

  • O OSS SDK não executa inspeção de segurança nem revisão de conteúdo nos arquivos enviados. Portanto, eventuais falhas no upload não têm relação com o conteúdo do arquivo.

Código de exemplo

O código a seguir 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 sobre upload retomável, visite o GitHub.